Go Fish: Using Chalk's Python Library to Plan Sales Reps' Road Trips
TL;DR
- What this is: how I used Chalk, an advanced Python library for feature engineering, to work out how many hours a sales rep will spend driving between national parks.
- How: I pulled National Park Service data, flagged the parks with fishing, measured the distance between every pair of parks and planned a road trip, all with Chalk features, resolvers and the
chalk queryCLI. - The answer, for California’s 28 parks: starting at Yosemite takes about 36 hours of driving; starting at Alcatraz takes 39.3. Where a rep is based saves real time and money.
- What I learned: in Chalk you describe what you want to know, and it wires the steps together for you. More below.
Prefer to watch? Here’s the 2-minute explainer I made for this project. It’s built with code too: React (Remotion) for the visuals and AI text-to-speech (Groq) for the narration.
The problem: go fish?
You want to help customers sell fishing gear, so you need to send traveling sales reps to the right places. To plan territories and budget travel, a sales manager needs to know how much time each rep will spend on the road driving to the parks in their region.
I started from a basic Chalk project with a Park model and one resolver that fetched park names from the National Park Service API, and extended it to answer that question.
What is Chalk?
Chalk is a feature-engineering platform for machine learning and real-time data. A “feature” is any fact about your data that a model or an app needs, like “does this park have fishing?” or “how far apart are these two parks?” Normally that means a tangle of SQL queries, scheduled jobs and caches. With Chalk, you write it in Python instead:
- Features (
@features) are Python classes that describe what you want to know. Chalk tracks, versions and serves each one. - Resolvers (
@online) are functions that compute features. Chalk connects them automatically by their inputs and outputs, so one resolver’s result feeds the next with no glue code. - Queries (
chalk queryfrom the command line) ask for any feature, and Chalk runs whichever resolvers it needs to answer.
Companies use it in production for things like fraud detection, identity checks and pricing, where answers have to come back fast. Here, it’s a neat way to turn raw park data into a business answer.
Step 1: Pull more from the parks API
The API already returns each park’s activities and GPS coordinates; the starter project just ignored them. First, the feature definitions in models.py:
@features
class Park:
id: str
description: str
has_long_description: bool
name: str
state_id: State.id
state: State
activities: list[str]
has_water: bool
has_fishing: bool
lat_long: str
The API returns activities as a list, so the feature is activities: list[str] (it gets parsed in the pipeline). Each state holds its parks and the drive times between them:
@features
class State:
id: str
parks: "DataFrame[Park]"
park_drive_times: "DataFrame[ParkPairDriveTime]"
park_count: int
And one feature class for each pair of parks in a state, for the distance math coming up:
@features
class ParkPairDriveTime:
id: str # "park1_id:park2_id"
state_id: State.id
state: State
park1_name: str
park2_name: str
distance_miles: float
drive_time_minutes: float
Then, in pipelines.py, the resolver that fetches parks now pulls activities and coordinates too:
@online
def get_parks() -> DataFrame[
Park.id, Park.name, Park.state_id, Park.description, Park.activities, Park.lat_long
]:
"""This function fetches some basics of the parks from the NPS API"""
response = requests.get(
"https://developer.nps.gov/api/v1/parks?limit=500&api_key=YOUR_NPS_API_KEY",
headers={"accept": "application/json"},
).json()
parks = []
for park in response["data"]:
parks.append(
Park(
id=park["parkCode"],
name=park["name"],
state_id=park["states"], # Keep as-is, e.g., "CA,NV"
description=park["description"],
activities=[a["name"] for a in park["activities"]],
lat_long=park["latLong"],
)
)
return DataFrame(parks)
Step 2: Flag the parks with fishing (and water)
Two small resolvers check each park’s activity list:
@online
def get_has_water(activities: Park.activities) -> Park.has_water:
"""Check if any activity contains the word 'water'"""
return any("water" in activity.lower() for activity in activities)
@online
def get_has_fishing(activities: Park.activities) -> Park.has_fishing:
"""Check if any activity contains the word 'fish'"""
return any("fish" in activity.lower() for activity in activities)
And one to count the parks in a state:
@online
def get_park_count(parks: State.parks[Park.id]) -> State.park_count:
"""Count the number of parks in a state"""
return len(list(parks))
Checking that Chalk registered the new features, for California:
chalk query --branch parks --in state.id=CA \
--out state.park_count \
--out state.parks.has_water
chalk query --branch parks --in state.id=CA \
--out state.park_count \
--out state.parks.has_fishing
state.park_count 28
state.parks.has_water [false,false,false,true,false,false,false,false,true,false,false,true,false,false,false,false,false,false,false,false,true,false,false,false,true,… (cut off in the terminal)
state.parks.has_fishing [false,false,false,true,false,true,false,true,true,false,false,true,false,false,false,false,false,true,false,false,true,false,false,false,true,false,true,true]
So 10 of California’s 28 parks offer fishing.
Step 3: Measure the distance between every pair of parks
The API gives coordinates as text like lat:37.58, long:-85.67, so first parse them:
def parse_lat_long(s: str) -> tuple[float, float] | None:
"""Parse 'lat:37.58, long:-85.67' format"""
if not s:
return None
try:
parts = s.split(", ")
lat = float(parts[0].replace("lat:", ""))
lon = float(parts[1].replace("long:", ""))
return lat, lon
except (ValueError, IndexError):
return None
Then the Haversine formula turns two sets of coordinates into miles (straight-line, across the curve of the Earth), and a simple 50 mph average turns miles into drive time:
def calc_distance_miles(
lat1: float, lon1: float, lat2: float, lon2: float
) -> float:
"""Calculate distance between two points using Haversine formula"""
R = 3959 # Earth's radius in miles
lat1, lat2, lon1, lon2 = map(math.radians, [lat1, lat2, lon1, lon2])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = (math.sin(dlat/2)**2
+ math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2)
c = 2 * math.asin(math.sqrt(a))
return R * c
def estimate_drive_time_minutes(distance_miles: float) -> float:
"""Estimate drive time assuming average 50 mph"""
return (distance_miles / 50) * 60
The resolver applies that to every pair of parks in a state. For California’s 28 parks, that’s 378 pairs:
@online
def get_park_drive_times(
state_id: State.id,
parks: State.parks[Park.id, Park.name, Park.lat_long]
) -> DataFrame[
ParkPairDriveTime.id, ParkPairDriveTime.state_id,
ParkPairDriveTime.park1_name, ParkPairDriveTime.park2_name,
ParkPairDriveTime.distance_miles, ParkPairDriveTime.drive_time_minutes,
]:
"""Calculate drive times between all pairs of parks in a state"""
park_list = list(parks)
drive_times = []
for park1, park2 in combinations(park_list, 2):
coords1 = parse_lat_long(park1[Park.lat_long])
coords2 = parse_lat_long(park2[Park.lat_long])
if coords1 and coords2:
distance = calc_distance_miles(
coords1[0], coords1[1], coords2[0], coords2[1]
)
drive_time = estimate_drive_time_minutes(distance)
drive_times.append(ParkPairDriveTime(
id=f"{park1[Park.id]}:{park2[Park.id]}",
state_id=state_id,
park1_name=park1[Park.name],
park2_name=park2[Park.name],
distance_miles=round(distance, 1),
drive_time_minutes=round(drive_time, 1),
))
return DataFrame(drive_times)
Tip: to have Chalk store these computed features, use the store-plan-stages=True flag. To see every pair’s drive time for California:
chalk query --branch parks --in state.id=CA \
--out state.park_drive_times
Step 4: Plan the road trip
To estimate a rep’s total hours on the road, I used a nearest-neighbor route: start at a park, drive to the closest park you haven’t visited, and repeat until you’ve seen them all. It isn’t the perfect route, but it’s fast and good enough for planning:
@online
def get_road_trip_hours_from_here(
park_id: Park.id,
park_lat_long: Park.lat_long,
state_parks: Park.state.parks[Park.id, Park.name, Park.lat_long]
) -> Park.road_trip_hours_from_here:
"""Hours to visit all parks in the state, starting from this park"""
parks_with_coords = []
start_park = None
start_coords = parse_lat_long(park_lat_long)
if not start_coords:
return 0.0
for p in list(state_parks):
coords = parse_lat_long(p.lat_long)
if coords:
if p.id == park_id:
start_park = (p, coords)
else:
parks_with_coords.append((p, coords))
if not start_park or len(parks_with_coords) < 1:
return 0.0
# Simple nearest-neighbor starting from this park
visited = [start_park]
unvisited = parks_with_coords
total_minutes = 0.0
while unvisited:
current = visited[-1]
nearest = None
nearest_dist = float('inf')
for candidate in unvisited:
dist = calc_distance_miles(
current[1][0], current[1][1], candidate[1][0], candidate[1][1]
)
if dist < nearest_dist:
nearest_dist = dist
nearest = candidate
total_minutes += estimate_drive_time_minutes(nearest_dist)
visited.append(nearest)
unvisited.remove(nearest)
return round(total_minutes / 60, 1)
Because it’s calculated per park, you can compare starting points:
chalk query --branch parks --in park.id=yose \
--out park.name \
--out park.road_trip_hours_from_here
chalk query --branch parks --in park.id=alca \
--out park.name \
--out park.road_trip_hours_from_here
park.name "Yosemite"
park.road_trip_hours_from_here 36.0
park.name "Alcatraz Island"
park.road_trip_hours_from_here 39.3
Starting from Yosemite saves about 3 hours compared with Alcatraz, because it’s more central. That’s the kind of answer a sales manager can use: where to base a rep, how many hours they’ll bill on the road, and what to budget for gas and travel.
Let’s go fish for some prospects!
What I learned
- Describe what you want, not how to wire it. Chalk chains resolvers by their inputs and outputs, so
activitiesflowed intohas_fishingwith no glue code. - Keep the math out of the resolvers. Plain helper functions (
parse_lat_long,calc_distance_miles,estimate_drive_time_minutes) are easy to test on their own. - Model at the level people ask questions. A
Statethat holds DataFrames of parks and drive times made state-level questions a single query. - “Good enough” beats perfect for planning. Nearest-neighbor isn’t the optimal route, but it’s fast and gives a manager a usable number.
What I’d improve
- Real road distances. Haversine is straight-line; a routing API (like Google Directions or OSRM) would give actual road miles.
- Fishing-only routes. The trip currently visits every park in a state; a production version would route only to parks with
has_fishing. - Multi-state regions. Some reps cover several states, which a
Regionfeature would handle. - Caching. The parks API is called on every query; Chalk’s offline resolvers are the natural next step.
The code
- Part 2: the video and the launch plan: how I’d launch this project like a DevRel
- pipelines.py and models.py
- The 2-minute explainer video on YouTube
- The full project, with the video’s source code and the DevRel launch plan: rkrevolution/a-feature-engineering-devrel-chalkai-example on GitHub
- Chalk’s developer docs, for the SDK and CLI: docs.chalk.ai
Technologies used
- Python 3.12
- Chalk:
@features,@onlineresolvers, DataFrames, branches, thechalk queryCLI and thechalkpySDK - National Park Service API (parks, activities and coordinates)
- requests (HTTP calls to the parks API)
- The Haversine formula (distance between GPS coordinates)
- A nearest-neighbor heuristic (road-trip routing)
- Remotion and Groq text-to-speech (the explainer video in the repo)

