Custom Resource
With an output in our desired schema, we can use the NREL API to lookup nearby alternative fuel stations. The NREL API is a standard REST API. In Dagster, we will create a resource with a single method to retrieve fuel stations. This method (alt_fuel_stations
) will take in the three parameters from our prompt engineering asset (latitude, longitude, and fuel type).
BASE_URL = "https://developer.nrel.gov/api/alt-fuel-stations/v1.json"
class NRELResource(dg.ConfigurableResource):
api_key: str = Field(description=("NREL API key. See https://developer.nrel.gov/signup/"))
def alt_fuel_stations(self, latitude: float, longitude: float, fuel_type: str = "all"):
if fuel_type not in {"BD", "ELEC", "all"}:
raise ValueError(f"{fuel_type} is not a valid fuel type")
url = "https://developer.nrel.gov/api/alt-fuel-stations/v1/nearest.json"
params = {
"api_key": self.api_key,
"latitude": latitude,
"longitude": longitude,
"radius": 5.0,
"fuel_type": fuel_type,
"status": "E",
}
resp = requests.get(url, params=params)
return resp.json()["fuel_stations"]
Now we can use our custom resource in another asset (nearest_fuel_station
) and query the API. The response of the API gives some very rich data about these fuel stations. One field that would be particularly interesting for the user is access_days_time
which shows when the fuel station is open.
@dg.asset(
kinds={"python"},
description="Find the nearest alt fuel stations",
)
def nearest_fuel_stations(nrel: NRELResource, user_input_prompt: UserInputSchema) -> list[dict]:
fuel_stations = nrel.alt_fuel_stations(
latitude=user_input_prompt.latitude,
longitude=user_input_prompt.longitude,
fuel_type=user_input_prompt.fuel_type,
)
nearest_stations_with_hours = []
for fuel_station in fuel_stations:
if fuel_station.get("access_days_time"):
nearest_stations_with_hours.append(fuel_station)
if len(nearest_stations_with_hours) == 3:
break
There is one problem with the access_days_time
value: it is a free form string and contains values like 7am-7pm M-Th and Sat, 7am-8pm F, 9am-5pm Sun
and 24 hour service
. We can write a function to parse this out, but that would get messy quickly. Instead, we can pass it through our AI model again and use a different prompt.
Next steps
- Continue this tutorial with additional prompt