The group wants an outdoor activity. You ask: “Will it rain while we’re in
Lisbon?” FieldTrip knows your dates, but an AI model alone cannot tell you the
latest forecast. It needs to look it up.
A tool is a piece of code the agent can ask to run. Here, one tool finds
Lisbon’s map coordinates; a second sends those coordinates and your dates to
Open-Meteo, a weather service. FieldTrip then turns the results into a readable
answer.
What you’ll add: two weather tools and instructions telling FieldTrip to
look up the city before asking for its forecast.
Under the hood: how a tool call works
defineTool describes a tool’s name, purpose, accepted inputs, and run function.
Valibot checks the model’s inputs before the code runs. The returned output
goes back to the model; a thrown error becomes a tool error it can respond to.
Passing the turn’s abort signal to fetch lets an interrupted turn cancel
the network request.
Create src/tools/weather.ts. It looks up the city and fetches a daily forecast,
then translates weather codes into words such as “clear sky”:
src
tools
weather.ts
Create this file. Create the parent folders if needed. In your code editor (for example, VS Code), open the file named above. Copy the code in Complete file, paste it into that file's editing pane, and save.
82: 'violent showers', 95: 'thunderstorm', 96: 'thunderstorm with hail', 99: 'severe thunderstorm with hail',
};
const isoDate = v.pipe(v.string(), v.isoDate());
export const getForecast = defineTool({
name: 'get_forecast',
description:
'Get the daily weather forecast (min/max °C, chance of rain, conditions) for a latitude/longitude between two dates (YYYY-MM-DD). Only works up to 16 days ahead. Get coordinates from geocode_city first.',
+ 82: 'violent showers', 95: 'thunderstorm', 96: 'thunderstorm with hail', 99: 'severe thunderstorm with hail',
+};
+
+const isoDate = v.pipe(v.string(), v.isoDate());
+
+export const getForecast = defineTool({
+ name: 'get_forecast',
+ description:
+ 'Get the daily weather forecast (min/max °C, chance of rain, conditions) for a latitude/longitude between two dates (YYYY-MM-DD). Only works up to 16 days ahead. Get coordinates from geocode_city first.',
What changes: a new module defines two tools that turn a city name and trip
dates into real weather data. The model chooses when to call them; their run
functions perform the network requests.
Walk through the change
Give each tool a contract.defineTool combines its name, description,
input schema, and implementation. Valibot checks the arguments before run
executes. v.isoDate() checks date format; the weather service still decides
whether that date falls within its forecast window.
Resolve the city first.geocode_city removes any comma-separated country
suffix, URL-encodes the name, and calls Open-Meteo’s geocoder. It returns
coordinates, country, and timezone for the first match. An empty result throws
a useful error instead of inventing a location.
Fetch and reshape the forecast.get_forecast sends the coordinates and
dates using URLSearchParams. The service returns parallel arrays; the
daily.time.map(...) loop combines matching indexes into one object per day.
WEATHER translates numeric condition codes into readable descriptions.
Handle interruption and failure. Both requests pass the turn’s signal
to fetch. Failed HTTP responses throw errors the model can respond to;
successful { output: ... } values go back into its context for the answer.
Follow it in the workshop: watch for a geocoding result followed by daily
forecast objects. An out-of-range date should produce an explained tool error,
not a guessed forecast.
Make the weather tools available to FieldTrip in src/agents/field-trip.ts.
The new instructions tell it to find the city’s coordinates first, then check
the forecast for the dates in the saved brief:
src
agents
field-trip.ts
Replace the entire contents of this file. In your code editor (for example, VS Code), open the file named above. Copy the code in Complete file, paste it into that file's editing pane, and save.
// Tools can write state. The write commits together with the tool call.
useTool({
name: 'save_trip_brief',
description:
'Save or update the offsite trip brief. Call this whenever the user states or changes the city, dates, headcount, budget, or interests. Only include fields the user mentioned; they are merged into the saved brief.',
return`You are FieldTrip, a helpful team-offsite planner. You help groups plan memorable offsites by understanding their destination, dates, headcount, budget, and interests.
Rules:
1. If the user's message contains ANY trip detail (city, dates, headcount, budget, interests), your FIRST action is to call \`save_trip_brief\` with those fields. Do this before writing any reply.
2. Answer questions about the trip from the saved brief below. If a detail is missing, ask for it.
3. For weather questions: call \`geocode_city\` for the city, then \`get_forecast\` with its latitude/longitude and the trip dates (use the saved brief). If there is no end date, use the start date. Summarise the forecast per day in plain words; if a tool returns an error, explain it to the user.
4. Keep replies short: at most 120 words unless the user asks for more detail.
import { useModel, usePersistentState, useTool } from '@flue/runtime';
import * as v from 'valibot';
+import { geocodeCity, getForecast } from '../tools/weather.ts';
// The trip brief the agent remembers for this conversation.
type TripBrief = {
@@ -42,16 +43,24 @@
},
});
+ // Tools that call an external API (Open-Meteo), defined in src/tools/weather.ts.
+ useTool(geocodeCity);
+ useTool(getForecast);
+
// The agent re-renders before every model call, so these instructions
// always reflect the latest saved brief.
const hasBrief = Object.keys(brief).length > 0;
+ const today = new Date().toISOString().slice(0, 10);
return `You are FieldTrip, a helpful team-offsite planner. You help groups plan memorable offsites by understanding their destination, dates, headcount, budget, and interests.
Rules:
1. If the user's message contains ANY trip detail (city, dates, headcount, budget, interests), your FIRST action is to call \`save_trip_brief\` with those fields. Do this before writing any reply.
2. Answer questions about the trip from the saved brief below. If a detail is missing, ask for it.
-3. Keep replies short: at most 120 words unless the user asks for more detail.
+3. For weather questions: call \`geocode_city\` for the city, then \`get_forecast\` with its latitude/longitude and the trip dates (use the saved brief). If there is no end date, use the start date. Summarise the forecast per day in plain words; if a tool returns an error, explain it to the user.
+4. Keep replies short: at most 120 words unless the user asks for more detail.
What changes: the planner imports and registers the weather tools, then adds
a rule describing the order in which to use them. Defining a tool in another
file does not automatically make it available to the agent.
Walk through the change
Mount both capabilities.useTool(geocodeCity) and useTool(getForecast)
expose their descriptions and input schemas to the model during each agent
render. The existing save_trip_brief tool still handles the trip facts.
Describe the dependency. The new weather rule says to run geocode_city
first, then pass its latitude and longitude to get_forecast. This is an
instruction to the model, not a hard-coded pair of function calls on every
incoming message.
Reuse the saved dates. The model can read the brief in its instructions.
It should use those dates and treat a missing end date as a one-day trip.
Including today also gives it a current-date reference for relative questions.
Separate data retrieval from explanation. The tools return structured
facts; the model turns them into a daily summary. The error rule tells it to
explain unavailable forecasts instead of filling gaps with invented data.
Follow it in the workshop: save the brief, then ask about weather without
repeating your dates. The tool arguments should use the saved dates and the
coordinates returned by geocoding.
npmrunsmoke--https://field-trip-agent.<subdomain>.workers.devcp3-live"Offsite in Lisbon from <START> to <END> for 14 people, budget 400 EUR each. We like food and hiking."
npmrunsmoke--https://field-trip-agent.<subdomain>.workers.devcp3-live"What's the weather forecast for our trip dates?"
The second turn should call geocode_city, then get_forecast with the returned
coordinates and dates from persistent state.
If both tool calls and ✔ completed appear without a prose summary, ask the
model to finish in the same conversation:
Terminal window
npmrunsmoke--https://field-trip-agent.<subdomain>.workers.devcp3-live"Please summarize that forecast for each day in plain language."
Optional depth check: exercise the error path in a fresh conversation:
Terminal window
npmrunsmoke--https://field-trip-agent.<subdomain>.workers.devcp3-live-err"What will the weather be in Lisbon on 2099-03-01?"
The forecast tool should fail clearly and the agent should explain the 16-day
limit instead of inventing weather.
This opens the same conversation as the smoke test. If you repeat this checkpoint, before copying its commands.
Start npm run dev in Terminal A and wait for VITE ... ready. Run in Terminal B:
Terminal window
npmrunsmoke--http://localhost:5173cp3-local"Offsite in Lisbon from <START> to <END> for 14 people, budget 400 EUR each. We like food and hiking."
npmrunsmoke--http://localhost:5173cp3-local"What's the weather forecast for our trip dates?"
The second turn should call geocode_city, then get_forecast with the returned
coordinates and dates from persistent state.
If the output shows both tool calls and ✔ completed but stops after the
get_forecast result, the tools worked and the model simply ended without prose.
Ask it to finish instead of rebuilding anything:
Terminal window
npmrunsmoke--http://localhost:5173cp3-local"Please summarize that forecast for each day in plain language."
Optional depth check: exercise the error path in a fresh conversation:
Terminal window
npmrunsmoke--http://localhost:5173cp3-local-err"What will the weather be in Lisbon on 2099-03-01?"
The forecast tool should fail clearly and the agent should explain the 16-day
limit instead of inventing weather.
This opens the same conversation as the smoke test. If you repeat this checkpoint, before copying its commands.
Verification gate
Prove it works
geocode_city runs before get_forecast.
The forecast uses the city’s map location and the dates in the trip notebook.
The reply summarizes each supported day in plain language.
Optional: an out-of-range date produces a tool error and no fabricated forecast.
Optional mini quizCheck your understanding: looking up the weather3 questions / instant feedback
Recovery lane
Get back on track in under a minute
If a dev server is running, stop it first. Uncommitted work is stashed and the current commit gets a backup branch before anything moves.
Option 01
Restart this exercise
Return to cp/2-hooks-state, rebuild this exercise, then use its Live deploy verification tab. Stop any running dev server with Ctrl+C before switching.