> ## Documentation Index
> Fetch the complete documentation index at: https://developers.kardinal.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> If you're integrating Kardinal into an application with an SDK, start with Integration paths: https://developers.kardinal.ai/getting-started/integration-paths.md. It lists the sections to read, in order. If you follow Integration paths, you don't need llms-full.txt or openapi.yaml. Each step links the section you need.

# Python SDK reference

> Every public class, method, and exception of the Kardinal Python SDK (kardinal-ai): signatures, the API endpoint behind each call, return values, and errors.

Reference for `kardinal-ai` 2.2.1. Install it with `pip install kardinal-ai`, import it as `kardinal`. Every method below is synchronous. The fields of a solution are in [Solution fields](#solution-fields). The fields of a plan are in the [API Reference](https://developers.kardinal.ai/api-reference/plan/create-a-plan.md).

## Client

### `Kardinal`

```python theme={null}
Kardinal(api_key=None, *, base_url=None, timeout=30, max_retries=3)
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `api_key` | `str` | `KARDINAL_API_KEY` | Your API key. Raises `MissingApiKeyError` if none is found, `EmptyApiKeyError` for `""`. |
| `base_url` | `str` | `KARDINAL_BASE_URL`, then `https://app.kardinal.ai/api/v2` | API host. Leave unset. |
| `timeout` | `float` | `30` | Seconds, applied by `httpx` to each phase of a request. |
| `max_retries` | `int` | `3` | Retries of a read, `update`, `replace`, `delete`, `start`, or `stop` after a network error, a `429`, or a `5xx`. |

The methods hang off `k.routing.plans` and `k.routing.solutions`. The client holds an `httpx` connection pool: use it as a context manager (`with Kardinal() as k:`) or call `k.close()`. See [Client configuration](https://developers.kardinal.ai/sdks/configuration.md).

### `whoami`

```python theme={null}
k.whoami() -> Whoami
```

[`GET /plans`](https://developers.kardinal.ai/api-reference/plan/retrieve-the-list-of-plans-in-a-light-representation), for one plan, with archived plans excluded. Returns a `Whoami` with `baseUrl` (`str`) and `agencyId` (`str`, or `None` when the API does not name an agency). It is free and retried like a read. See [Checking the key at startup](https://developers.kardinal.ai/sdks/configuration.md#checking-the-key-at-startup).

## Plans

`submit`, `update`, and `replace` log one line for each kind of API warning on the `kardinal` logger, at the `WARNING` level. Python prints these lines on stderr even if you set up no logging. To silence them, call `logging.getLogger("kardinal").setLevel(logging.ERROR)`. To read the warnings in your program, use the `.warnings` attribute of the returned `Plan`. See [Warnings on successful calls](https://developers.kardinal.ai/sdks/errors-and-warnings.md#warnings-on-successful-calls).

### `plans.submit`

```python theme={null}
k.routing.plans.submit(plan: PlanCreate, *, allow_unknown: Collection[str] = ()) -> Plan
```

[`POST /plans`](https://developers.kardinal.ai/api-reference/plan/create-a-plan). Creates the plan and starts its optimization. Returns the stored `Plan`, with the `id` the server assigned and `.warnings`. Raises `UnknownFieldError`, before sending, for a key no model declares, unless named in `allow_unknown`. Consumes credits with a production key. **Never retried.**

### `plans.get`

```python theme={null}
k.routing.plans.get(plan_id: str) -> Plan
```

[`GET /plans/{planId}`](https://developers.kardinal.ai/api-reference/plan/retrieve-a-plan). Returns the plan as currently stored. Raises `KardinalNotFoundError` if it doesn't exist.

### `plans.update`

```python theme={null}
k.routing.plans.update(plan: Plan, *, force: bool = False, allow_unknown: Collection[str] = ()) -> Plan
```

[`PUT /plans/{planId}`](https://developers.kardinal.ai/api-reference/plan/update-a-plan). Replaces the whole plan: anything left out is removed. The version increments, and the plan is re-optimized, only if the content changed; an identical update is a free no-op. Fields unknown to this SDK version that `get` read are sent back untouched; a key you added that no model declares raises `UnknownFieldError`, unless named in `allow_unknown`. On a plan not read from the API, a likely typo only emits an `UnknownFieldWarning`. `force=True` unarchives an archived plan first. Retried.

### `plans.replace`

```python theme={null}
k.routing.plans.replace(plan_id: str, plan: PlanCreate, *, force: bool = False, allow_unknown: Collection[str] = ()) -> Plan
```

[`PUT /plans/{planId}`](https://developers.kardinal.ai/api-reference/plan/update-a-plan). Replaces the whole plan from a `PlanCreate`, the input that `submit` takes. You have no `id`, `agencyId`, or `version` to copy. A field that the API gained after this SDK version is removed, so use `get` and `update` when you need to keep it. A `Plan` that you read with `get` raises `TypeError` before any request. An identical plan is a free no-op and keeps the same version. A plan created from raw JSON gets one new version the first time. There is no version check, so the last write wins. Raises `UnknownFieldError` as `submit` does. `force=True` unarchives an archived plan first. Retried. See [Replacing a plan from your own data](https://developers.kardinal.ai/sdks/plan-lifecycle.md#replacing-a-plan-from-your-own-data).

### `plans.delete`

```python theme={null}
k.routing.plans.delete(plan_id: str) -> None
```

[`DELETE /plans/{planId}`](https://developers.kardinal.ai/api-reference/plan/delete-a-plan). Permanently deletes the plan and its solution, and stops any optimization in progress. Retried.

### `plans.list`

```python theme={null}
k.routing.plans.list(*, page: int = 1, items_per_page: int = 20, archived: Literal["excluded", "included", "only"] = "excluded") -> Page[PlanLight]
```

[`GET /plans`](https://developers.kardinal.ai/api-reference/plan/retrieve-the-list-of-plans-in-a-light-representation). Returns one page of plans, in their light form. A page past the last one returns the last page.

### `plans.iter_all`

```python theme={null}
k.routing.plans.iter_all(*, archived: Literal["excluded", "included", "only"] = "excluded") -> Iterator[PlanLight]
```

`GET /plans`, every page. Iterates over every plan, fetching pages as it goes.

### `plans.start`

```python theme={null}
k.routing.plans.start(plan_id: str, *, force: bool = False) -> EnvelopedPlanReference
```

[`PUT /plans/{planId}/running`](https://developers.kardinal.ai/api-reference/plan/stop-or-restart-the-optimization-of-a-plan). Restarts the optimization of the current version, without changing its content or version. Returns `agencyId`, `planId`, `planVersion`, and `warnings`. Retried.

### `plans.stop`

```python theme={null}
k.routing.plans.stop(plan_id: str, *, force: bool = False) -> EnvelopedPlanReference
```

[`PUT /plans/{planId}/running`](https://developers.kardinal.ai/api-reference/plan/stop-or-restart-the-optimization-of-a-plan). Stops the optimization in progress, without changing the plan's content or version. Retried.

### `plans.get_status`

```python theme={null}
k.routing.plans.get_status(plan_id: str) -> PlanState
```

[`GET /plans/{planId}/state`](https://developers.kardinal.ai/api-reference/plan/retrieve-the-latest-state-of-a-plan). Returns the plan's current state, a single value: `waiting`, `processing`, `optimizing`, `optimized`, `stopped`, `interrupted`, and so on. It always returns a `PlanState`, even for a state this SDK version doesn't know yet: that state comes back as a `PlanState` that equals its raw string. Not the detailed `PlanStatus` object found in `Plan.status`.

## Solutions

### `solutions.wait`

```python theme={null}
k.routing.solutions.wait(plan_id: str, timeout: float | None = None) -> Solution
```

`GET /plans/{planId}/state`, then [`/solution`](https://developers.kardinal.ai/api-reference/solution/retrieve-a-plan-solution). Blocks until the optimization of the current version is over, then returns its solution. Reads the state every 10 seconds at first, up to every 60 seconds. `solution.final_state` tells how it ended: `optimized`, `interrupted`, or `stopped`. Raises `KardinalOptimizationError` (`NO_SOLUTION`, `PLAN_SUPERSEDED`, `OPTIMIZATION_STALLED`), `KardinalNotFoundError` if the plan is deleted meanwhile, and `KardinalTimeoutError` once `timeout` seconds have elapsed. See [Waiting for the solution](https://developers.kardinal.ai/sdks/plan-lifecycle.md#waiting-for-the-solution).

### `solutions.get`

```python theme={null}
k.routing.solutions.get(plan_id: str) -> Solution
```

[`GET /plans/{planId}/solution`](https://developers.kardinal.ai/api-reference/solution/retrieve-a-plan-solution). Returns the current best solution right away, without waiting. Raises `KardinalNotFoundError` until the engine has a first solution.

### `solutions.get_objectives`

```python theme={null}
k.routing.solutions.get_objectives(plan_id: str) -> SolutionObjectives
```

[`GET /plans/{planId}/solution/objectives`](https://developers.kardinal.ai/api-reference/solution/retrieve-the-objectives-of-a-plan-solution). Returns the value of each objective, without the tours: a plain `list` of `SolutionObjective`, with a `.warnings` attribute.

### Solution fields

`solution.tours` holds one `Tour` per resource used. `tour.wayPoints` is a list of `WayPointBegin`, `WayPointStop`, `WayPointBreak`, and `WayPointEnd` objects, from `kardinal.routing.models`. Read `wp.type` (`"begin"`, `"stop"`, `"break"`, or `"end"`) before you read a field.

Every field in these tables except `type` is optional: it is `None` when the API leaves it out. The SDK returns dates and durations as `str` and does not convert them.

A date is the local time of the plan's `tz`, with its offset and seconds, for example `2026-11-20T08:01:23+01:00`. If the plan has no `tz`, the date is in UTC, with a `Z`. The `solution.timestamp` is always in `Z`. See [Dates and time zones](https://developers.kardinal.ai/reference/data-model.md#dates-and-time-zones). To get a `datetime`, write `datetime.fromisoformat(value.replace("Z", "+00:00"))`, which also works on Python 3.10.

A duration is an ISO 8601 string such as `PT5H11M55S`. The Python standard library has no parser for it.

| Tour field | Type | Description |
| - | - | - |
| `resourceId` | `str` | The resource that drives this tour. |
| `isValid` | `bool` | Whether the tour respects every hard constraint. A valid tour can still be late: read `totalDelay` and the `delay` of each stop. |
| `distanceInKm` | `float` | Total distance of the tour. |
| `travelDuration` | `str` (duration) | Total time spent driving. |
| `workingDuration` | `str` (duration) | Total working time of the tour. |
| `waitingDuration` | `str` (duration) | Total time spent waiting. |
| `totalDelay` | `str` (duration) | Sum of the delays of the tour. |
| `wayPoints` | `list` | The waypoints of the tour, in order. |

| Waypoint field | Type | `begin` | `stop` | `break` | `end` | Description |
| - | - | - | - | - | - | - |
| `type` | `str` | ✓ | ✓ | ✓ | ✓ | `"begin"`, `"stop"`, `"break"`, or `"end"`. |
| `stopId` | `str` | — | ✓ | — | — | The `id` of the stop. |
| `status` | `WayPointStatus`, a `str` enum | ✓ | ✓ | ✓ | ✓ | The status of the waypoint: `"fixed"`, `"assigned"`, or `"optimized"`. |
| `arrivalTime` | `str` (date) | — | ✓ | ✓ | ✓ | When the vehicle gets there. |
| `beginTime` | `str` (date) | — | ✓ | — | — | When the service starts. It is later than `arrivalTime` when the vehicle waits for the time window to open. |
| `departureTime` | `str` (date) | ✓ | ✓ | ✓ | — | When the vehicle leaves. |
| `delay` | `str` (duration) | — | ✓ | — | — | The delay on the stop. It is `PT0S` for a stop served on time. |
| `fromPrevious` | `FromPrevious` | ✓ | ✓ | ✓ | ✓ | The leg from the previous waypoint: `travelDistanceInKm` (`float`) and `travelDuration` (`str`). |

The span of a break waypoint, from `arrivalTime` to `departureTime`, can be longer than the break, because it includes any wait before the break. For example, a 30-minute break can show 10:10 to 12:30. See [Breaks](https://developers.kardinal.ai/guides/breaks.md).

`solution.totalDelay` sums the delays, and `solution.unaffectedStopIds` lists the stops left out. Capacities, violations, and properties are in the [API Reference](https://developers.kardinal.ai/api-reference/solution/retrieve-a-plan-solution.md).

## Examples

### `examples.small_delivery_plan`

```python theme={null}
from kardinal.routing import examples

examples.small_delivery_plan() -> PlanCreate
```

A ready-to-submit plan: two resources, eight single-stop orders around central Paris, and a 10-second optimization. The working window starts tomorrow at 8:00. Each call returns a new object.

### `examples.cold_chain_plan`

```python theme={null}
examples.cold_chain_plan() -> PlanCreate
```

The plan of the [cold-chain last-mile](https://developers.kardinal.ai/case-studies/cold-chain-last-mile.md) case study, as a typed object that you adapt to your data. Each call returns a new object.

### `examples.parcel_express_plan`

```python theme={null}
examples.parcel_express_plan() -> PlanCreate
```

The plan of the [parcel express](https://developers.kardinal.ai/case-studies/parcel-express.md) case study, as a typed object that you adapt to your data. Each call returns a new object.

## Local checks

### `unknown_fields`

```python theme={null}
from kardinal.routing import unknown_fields

unknown_fields(plan) -> list[UnknownField]
```

Runs the check `submit` makes, without sending anything: every key no model declares, with its path and, when one is close, the real field name it was likely meant to be. Empty when the plan is clean.

## Types

### `PlanCreate`

From `kardinal.routing.plans`. The plan you submit: no `id`, the server assigns it. Built from `kardinal.routing.models` objects, or loaded from JSON with `PlanCreate.model_validate_json(text)`. Its orders are `kardinal.routing.plans.Order` objects.

### `Plan`

From `kardinal.routing.plans`. The plan as stored, returned by `submit`, `get`, `update`, and `replace`: the same content plus `id`, `version`, `status`, `state`, and `agencyId`, and `.warnings` from the call that returned it.

### `Page`

From `kardinal`. Returned by `plans.list`: `items`, `page`, `total_pages`, `total`, `next_page` (`None` on the last page), `previous_page` (`None` on the first page), and `items_per_page`.

### Model types

`kardinal.routing.models` holds a `pydantic` model for every schema of the [API specification](https://developers.kardinal.ai/api-reference/plan/create-a-plan.md) (`Resource`, `SingleStop`, `AlternativesStop`, `Position`, `TimeWindow`, `Solution`, `Tour`, `Warning`, and so on), with the API's field names and descriptions.

## Exceptions

All importable from `kardinal`, all subclasses of `KardinalError`. See [Errors, retries, and warnings](https://developers.kardinal.ai/sdks/errors-and-warnings.md).

| Exception | Raised on |
| - | - |
| `KardinalAuthError` | `401`. From 1.1.0, also a `403` for a revoked or regenerated key. |
| `KardinalLimitError` | A `403` recognized as a limit: plan size, quota, or credits. In 1.0.x, any `403`. |
| `KardinalForbiddenError` | From 1.1.0, any other `403`. |
| `KardinalValidationError` | `400`. From 1.1.0, also the `403` of an archived plan without `force`. |
| `KardinalNotFoundError` | `404` |
| `KardinalRateLimitError` | `429` |
| `KardinalServerError` | `5xx` |
| `KardinalConnectionError` | No HTTP response |
| `KardinalTimeoutError` | `solutions.wait` time limit elapsed |
| `KardinalOptimizationError` | `solutions.wait` has no solution to return |
| `UnknownFieldError` | Unknown key found before sending |
| `MissingApiKeyError`, `EmptyApiKeyError` | No usable key when creating the client |

`UnknownFieldWarning`, also importable from `kardinal`, is a warning, not an exception: see [Client-side errors](https://developers.kardinal.ai/sdks/errors-and-warnings.md#client-side-errors).

Every exception carries `.code`, `.status`, `.errors`, `.details`, `.retryable`, `.warnings`, and `.request_id`.

## Known limitations

* The client is synchronous; there's no `asyncio` client.
* `pydantic` converts a string holding a number or a boolean (`"1"`, `"true"`) instead of refusing it.
* `.request_id` is usually `None`: the API sends an `X-Request-Id` header only on some responses.
* The `kardinal` command needs the `cli` extra: `pip install "kardinal-ai[cli]"`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.