Skip to content

6. Agent tracing

Checkpoint 6 of 67 minutes

Agent tracing

Replay a weather question, follow the steps behind the answer, and see where time was spent.

FieldTrip now remembers the trip, checks the weather, researches places, and writes files. But what if an answer takes a long time? Was the model thinking, or was the weather service slow?

This step gives you a recording and a timeline. Session replay lets you follow the messages and tool calls behind an answer. A trace shows how those steps fit together and how long each took. A log adds a small note from your code, such as how many forecast days came back.

What you’ll add: settings to collect logs and traces, plus one forecast log. Then you’ll ask a weather question and follow its journey in the dashboard.

Under the hood: the labels you’ll see in a trace

Flue 2.0.0 and newer adds agent tracing automatically. Each timed section is called a span: invoke_agent covers the response, chat covers a model call, and execute_tool covers a tool call. The trace links these sections to show which operation called which. This checkpoint enables Workers Logs and Traces in wrangler.jsonc and adds one structured forecast log in src/tools/weather.ts. Flue installs its tracing adapter at build time, so no manual observe() callback is needed.

Update wrangler.jsonc to enable Workers Logs and Traces. No observability SDK is required:

  • wrangler.jsonc

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.

wrangler.jsonc
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "field-trip-agent",
// Flue requires nodejs_compat and a compatibility_date of 2026-04-01 or newer.
"compatibility_date": "2026-09-01",
"compatibility_flags": ["nodejs_compat"],
// Workers AI binding: powers `cloudflare/@cf/...` models. No API keys needed.
// AI always runs remotely (even in `vite dev`), so `remote: true` is explicit.
"ai": {
"binding": "AI",
"remote": true
},
// Durable Object migrations. Flue generates one DO class per agent
// (FieldTrip -> FlueFieldTripAgent), but YOU own the migration history.
// Checkpoint 1 adds the first entry here. Append; never rewrite deployed entries.
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": ["FlueFieldTripAgent"]
},
{ "tag": "v2", "new_sqlite_classes": ["Sandbox"] }
],
// cp5: container sandbox (class exported from src/cloudflare.ts, image from ./Dockerfile).
"durable_objects": { "bindings": [{ "name": "Sandbox", "class_name": "Sandbox" }] },
"containers": [{ "class_name": "Sandbox", "image": "./Dockerfile", "max_instances": 10 }],
// cp6: Workers Logs + Traces (Cloudflare Agents and consolidated Observability).
"observability": { "enabled": true, "traces": { "enabled": true } }
}

Update src/tools/weather.ts to record how many forecast days came back. Complete file includes both existing weather tools with that one log added, ready to replace the file. Choose Changes to see where the log was inserted:

  • src
    • tools
      • weather.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.

src/tools/weather.ts
import { defineTool } from '@flue/runtime';
import * as v from 'valibot';
// Open-Meteo: free, no API key. https://open-meteo.com/en/docs
export const geocodeCity = defineTool({
name: 'geocode_city',
description:
'Look up a city by name and return its latitude, longitude, country and timezone. Call this before get_forecast.',
input: v.object({
city: v.pipe(v.string(), v.minLength(2), v.description('City name only, e.g. "Lisbon"')),
}),
async run({ data, signal }) {
// The geocoder matches names only, so "Lisbon, Portugal" -> "Lisbon".
const name = data.city.split(',')[0].trim();
const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(name)}&count=1&language=en&format=json`;
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`Geocoding failed: HTTP ${res.status}`);
const body = (await res.json()) as {
results?: Array<{ name: string; country: string; latitude: number; longitude: number; timezone: string }>;
};
const place = body.results?.[0];
// Throwing turns into a tool error the model can see and recover from.
if (!place) throw new Error(`No city found named "${name}". Ask the user to check the spelling.`);
return {
output: {
name: place.name,
country: place.country,
latitude: place.latitude,
longitude: place.longitude,
timezone: place.timezone,
},
};
},
});
// WMO weather codes -> short descriptions, so the model doesn't have to guess.
const WEATHER: Record<number, string> = {
0: 'clear sky', 1: 'mainly clear', 2: 'partly cloudy', 3: 'overcast', 45: 'fog', 48: 'rime fog',
51: 'light drizzle', 53: 'drizzle', 55: 'dense drizzle', 61: 'light rain', 63: 'rain', 65: 'heavy rain',
71: 'light snow', 73: 'snow', 75: 'heavy snow', 80: 'rain showers', 81: 'heavy showers',
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.',
input: v.object({
latitude: v.number(),
longitude: v.number(),
startDate: isoDate,
endDate: isoDate,
}),
async run({ data, signal }) {
const params = new URLSearchParams({
latitude: String(data.latitude),
longitude: String(data.longitude),
daily: 'temperature_2m_max,temperature_2m_min,precipitation_probability_max,weather_code',
start_date: data.startDate,
end_date: data.endDate,
timezone: 'auto',
});
const res = await fetch(`https://api.open-meteo.com/v1/forecast?${params}`, { signal });
if (!res.ok) {
const reason = ((await res.json().catch(() => ({}))) as { reason?: string }).reason;
const today = new Date().toISOString().slice(0, 10);
throw new Error(
`Forecast unavailable for ${data.startDate}..${data.endDate}: ${reason ?? `HTTP ${res.status}`}. ` +
`Forecasts only cover today (${today}) up to 16 days ahead.`,
);
}
const { daily } = (await res.json()) as {
daily: {
time: string[];
temperature_2m_min: number[];
temperature_2m_max: number[];
precipitation_probability_max: number[];
weather_code: number[];
};
};
console.log({ event: 'forecast', latitude: data.latitude, longitude: data.longitude, days: daily.time.length }); // cp6: Workers Logs
return {
output: daily.time.map((date, i) => ({
date,
minC: daily.temperature_2m_min[i],
maxC: daily.temperature_2m_max[i],
rainChancePct: daily.precipitation_probability_max[i],
conditions: WEATHER[daily.weather_code[i]] ?? `code ${daily.weather_code[i]}`,
})),
};
},
});

The trace already records the tool boundary and outbound fetch. This log adds the application fact that a forecast was successfully parsed and how many days it contained. It is diagnostic data, not model context.

3. Ask a weather question to record its journey

Section titled “3. Ask a weather question to record its journey”

Trip dates are filled automatically in the commands and their copy buttons. The guide reuses your workshop dates.

Terminal window
npm run typecheck
npm run deploy
sleep 5
npm run smoke -- https://field-trip-agent.<subdomain>.workers.dev cp6-live "Offsite in Lisbon from <START> to <END> for 14 people. Save the brief, then check the weather."

Use a fresh conversation ID and the exact deployed URL. The response should save the brief, call geocode_city, call get_forecast, and return the forecast.

Save your workers.dev subdomain to open this test ↗https://field-trip-agent.<subdomain>.workers.dev/?id=cp6-live

This opens the same conversation as the smoke test. If you repeat this checkpoint, before copying its commands.

After the live response completes, allow a couple of minutes for ingestion and refresh if the latest run is not visible yet:

  1. Open Agents in the Cloudflare dashboard.
  2. Select FieldTrip, then open the newest session whose conversation ID starts with cp6-live-.
  3. Use Session replay to follow the user message, model output, and tool calls in order.
  4. Confirm that the replay shows save_trip_brief, geocode_city, and get_forecast.

Session replay answers what happened. The trace waterfall answers where time was spent and which operation called which.

Open Trace for the same turn:

  1. Expand invoke_agent FieldTrip, the span for the complete response.
  2. Inspect each chat @cf/google/gemma-4-26b-a4b-it span for latency and token usage.
  3. Inspect execute_tool save_trip_brief, execute_tool geocode_city, and execute_tool get_forecast.
  4. Expand get_forecast and follow its outbound fetch to Open-Meteo.
  5. Compare the span durations. Do not add parent and child durations because they overlap.

The admission POST returns before the durable response finishes. The agent run in the Agents dashboard is the complete turn, not only that short HTTP request.

6. Find the forecast note for the same run

Section titled “6. Find the forecast note for the same run”

Open the account-level Observability dashboard:

  1. Filter to the field-trip-agent Worker and the time range of your cp6-live-… run.
  2. In Events, filter event = forecast and open the successful forecast log.
  3. Open the correlated trace from the event context.
  4. Confirm that the same execution contains execute_tool get_forecast and its Open-Meteo fetch.

Use Agents for the agent-native session replay and trace waterfall. Use the consolidated Observability view when you need agent spans, Worker invocations, subrequests, and application logs in one operational investigation.

Verification gate

Prove it works

  • FieldTrip answers the weather question successfully.
  • Session replay shows it saving the brief, finding the city, and checking the forecast.
  • The timeline shows the whole reply (invoke_agent), model calls (chat), and tool calls (execute_tool).
  • You can see how long the model took and how many tokens it used.
  • You can follow the weather tool’s request to Open-Meteo.
  • The Observability dashboard shows your forecast note for the same run.
Optional mini quizCheck the execution story3 questions instant feedback
1Which view helps you find where an answer spent its time?
2Which view is best for reading the conversation and tool calls in order?
3What does the forecast log add?
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/5-sandbox, rebuild this exercise, then use its Live deploy verification tab. Stop any running dev server with Ctrl+C before switching.

Terminal
git stash push --include-untracked -m "workshop recovery"
git fetch origin
git branch -f workshop-backup HEAD
git switch --no-track -C workshop origin/cp/5-sandbox
npm ci
Option 02

Catch up with the room

Jump to cp/6-iterate-observe, then use this checkpoint's Live deploy verification tab. Stop any running dev server with Ctrl+C before switching.

The catch-up commands retain the agent from cp/5-sandbox, keeping the on-demand workspace optimization in the bonus assignment.

Terminal
git stash push --include-untracked -m "workshop recovery"
git fetch origin
git branch -f workshop-backup HEAD
git switch --no-track -C workshop origin/cp/6-iterate-observe
git restore --source=origin/cp/5-sandbox -- src/agents/field-trip.ts
npm ci

The completed upstream branch already enables traces. The catch-up commands keep the checkpoint-5 agent so the on-demand workspace change remains a bonus exercise.

References: Cloudflare Agent tracing, Flue Cloudflare observability.

Next: Finish and verify the complete agent →