PlanSolve for Python
Official Python client for the PlanSolve optimization API. One typed client covers three solvers (field service routing, professional-services task assignment, and shift scheduling) with built-in polling and clean error messages.
Installation
pip install plansolve
Requires Python 3.8+ and requests 2.31+. Type hints are bundled.
Quick start
from plansolve import PlanSolveClient
client = PlanSolveClient(api_key="YOUR_API_KEY")
request = {
"vehicles": [
{
"id": "tech1",
"location": [40.7128, -74.0060],
"skills": ["repair"],
"shifts": [
{"id": "morning", "minStartTime": "2026-04-02T08:00:00", "maxEndTime": "2026-04-02T17:00:00"}
],
}
],
"visits": [
{
"id": "visit1",
"name": "AC Repair - Downtown Office",
"location": [40.7589, -73.9851],
"serviceDuration": "PT60M",
"priority": "HIGH",
"requiredSkills": ["repair"],
"timeWindows": [
{"minStartTime": "2026-04-02T09:00:00", "maxEndTime": "2026-04-02T17:00:00"}
],
}
],
}
# Submit and block until the optimized plan is ready
result = client.field_service.start_and_wait_for_completion(request)
for vehicle in result.vehicles:
print(f"Vehicle {vehicle.id}: {len(vehicle.visits)} visits")
Requests accept a plain dict (as above) or the typed dataclasses (FieldServiceRequest, Vehicle, Visit, ...).
Solvers
One client, three solvers. All share the same submit, poll, result workflow:
| Solver | Accessor | Use for |
|---|---|---|
| Field Service | client.field_service |
Vehicle routing with travel time, time windows, and skills |
| Professional Services | client.professional_services |
Task assignment by skill, availability, priority, and deadlines |
| Shift | client.shift |
Shift scheduling across contracts, availability, and fairness |
Every solver client exposes the same methods:
| Method | HTTP | Returns |
|---|---|---|
start(request) |
POST /api/v1/{solver} |
Start response with job_id (solver_job_id and result are None unless the server provides them) |
get_status(job_id) |
GET /api/v1/{solver}/{job_id}/status |
Status dict (jobId, solverStatus, score, feasible, solving) — score here is still the raw wire value, not a Score; see Score below |
get_result(job_id) |
GET /api/v1/{solver}/{job_id} |
The solver's result type |
stop(job_id) |
DELETE /api/v1/{solver}/{job_id} |
Stops the solve and returns the best solution found so far (same type as get_result). A job still waiting in the queue is cancelled instead and raises JobCancelledError |
analyze(job_id) |
GET /api/v1/{solver}/{job_id}/analyze |
ScoreAnalysisResponse: total score, initialized and per-constraint ConstraintAnalysisResponse (name, package, weight, score, match_count, matches). Scores and weights are parsed into Score; each match's justification is the raw, solver-specific JSON. Raises HTTPError 409 while the job is still running and 422 when it failed, was lost or was cancelled |
wait_for_completion(job_id, poll_interval_ms=5000, max_attempts=150) |
polls status, then fetches the result | The solver's result type |
start_and_wait_for_completion(request, poll_interval_ms=5000, max_attempts=150) |
start + wait_for_completion |
The solver's result type |
{solver} is fieldservice, professionalservices or shift. The result types are FieldServiceResultResponse, ProfessionalServicesResultResponse and ShiftResultResponse; each gets a client-side job_id stamped after parsing.
Score
Score is an exported dataclass with hard, medium and soft levels (arbitrary-precision int); a solution is feasible when hard >= 0. Use Score.parse(value) to parse the canonical "Xhard/Ymedium/Zsoft" string, Score.from_wire(value) to normalize either wire form (and None/"" into None), score.to_wire_object() to render the object form back out, and str(score) for the canonical string.
On get_result, stop and wait_for_completion, the score field on the typed result dataclasses is Optional[Score]: None while the job is still solving, and also for a job the solver has not scored yet.
get_status is the one exception. SolverStatusResponse is just a Dict[str, Any] type alias, not a model, so it is never run through Score.from_wire. Its score key is still the raw string or object the server sent, exactly like before this change — unlike every other SDK's status response, and unlike this SDK's own typed result responses. Parse it yourself:
from plansolve import Score
status = client.field_service.get_status(job_id)
score = Score.from_wire(status.get("score")) # None while solving or unscored
if score is not None:
print(f"{score} (feasible: {score.hard >= 0})")
Polling
The wait helpers sleep poll_interval_ms before each status check and stop as soon as the status reports solving false and solverStatus NOT_SOLVING (a score is not required). The defaults are 5000 ms between polls and 150 polls (12.5 minutes), which covers the server's 10-minute cap on a solve. A value of 0 or less for either argument falls back to the default.
# Stop early and keep the best plan found so far
best = client.shift.stop(job_id)
# Inspect which constraints drive the score
analysis = client.field_service.analyze(job_id)
for constraint in analysis.constraints or []:
print(f"{constraint.name}: {constraint.score} ({constraint.match_count} matches)")
A shift result's assigned_shifts and unassigned_shifts are lists of ShiftAssignment, each with name, from_time, to_time and the assigned_employee the solver chose (None for an unassigned shift). A shift with value > 1 is listed once per position ("morning#1", "morning#2"). shifts holds every position, assigned or not:
result = client.shift.get_result(job_id)
for shift in result.assigned_shifts:
print(f"{shift.name}: {shift.from_time} -> {shift.to_time} ({shift.assigned_employee})")
print(f"{len(result.unassigned_shifts)} shift(s) could not be filled")
The Jobs API returns JobDto.status as a JobStatus (PENDING, SUCCEEDED, FAILED, LOST, CANCELLED) and JobDto.solver_type as a SolverType (FIELD_SERVICE 0, SHIFT 1, PROFESSIONAL_SERVICES 2). A value the SDK does not name yet is kept as a plain int instead of raising.
Unassigned work parses cleanly: a field service visit the solver could not place comes back with vehicle, arrival_time, departure_time, start_service_time and driving_time_seconds_from_previous_standstill set to None.
Configuration
Pass your API key to the constructor: PlanSolveClient(api_key="..."). It is sent as the X-API-KEY header on every request.
Error handling
The SDK never prints to stdout or stderr; everything is reported through exceptions:
| Exception | When |
|---|---|
requests.HTTPError |
Any non-2xx response. The message is HTTP <status>: <detail>, built from the error body (validation errors, error, message, detail or title), e.g. HTTP 400: vehicles: At least one vehicle is required. The original response is on e.response. A failed solve answers the status endpoint with HTTP 422, so the wait helpers raise this too. |
ValueError("JobId was not returned from wait_for_completion.") |
wait_for_completion was called with an empty job id, or the start response carried none. |
ValueError("Solver still running after N polls; raise max_attempts or lower options.spent_limit") |
The solver was still running after max_attempts status polls. |
JobCancelledError |
stop was called on a job still waiting in the queue: the job was cancelled before solving started and no plan exists. Carries job_id and message. |
requests.RequestException |
Network failures (connection errors, timeouts) raised by requests. |
import requests
try:
result = client.field_service.start_and_wait_for_completion(request)
except requests.HTTPError as e:
print(e.response.status_code, e)
except ValueError as e:
print(e)
Documentation
Full guides, per-solver data models, and parameter reference live on the docs site:
- Field Service: https://getplansolve.com/docs/fieldservice/sdk/python
- Professional Services: https://getplansolve.com/docs/professionalservices/sdk/python
- Shift: https://getplansolve.com/docs/shiftsolver/sdk/python
Package: PyPI
License
Apache-2.0. See LICENSE.
Metadata
Release files for plansolve 0.37.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 | |
|---|---|---|---|
| plansolve-0.37.0.tar.gz | 55.7 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| plansolve-0.37.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 107.3 kB
Release files / plansolve-0.37.0.tar.gz
| Download URL | plansolve-0.37.0.tar.gz |
|---|---|
| Size | 55.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
37cd3230c360430a1aa6391c9bd18f8c0f98b7ef21b8411f29e1512c5192ff48
|
|
BLAKE2b-256 checksum How to use checksums |
3cbae6bce09f5cc6f0dc08b282f9ced3cc459ebcba756e7af8e58233066b6bfb
|
| 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 Oct 18, 2026.
Transparency logRelease files / plansolve-0.37.0-py3-none-any.whl
| Download URL | plansolve-0.37.0-py3-none-any.whl |
|---|---|
| Size | 51.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2e2bfa24fb5108a71698401c5b0b37d224189240c1603cba190a8f83a9002357
|
|
BLAKE2b-256 checksum How to use checksums |
3d464144f41bf738f3f12301f9471c2f7592789ffb5227c1ce8297bba1b5cbcd
|
| 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 Oct 18, 2026.
Transparency log