Skip to content

4. Venue-scout subagent

Checkpoint 4 of 68 minutes

Venue-scout subagent

Find three places, ask a research assistant to assess them, and get suggestions with sources.

Now the team asks: “Where should we go?” FieldTrip can find nearby places, but reading up on each one is a separate job. Let’s give the planner a research assistant, the venue scout.

FieldTrip chooses three candidates and hands the scout a brief: the place names, city, group size, and interests. The scout reads Wikipedia summaries and sends back an assessment with links. FieldTrip uses that report to suggest a plan. This focused helper is called a subagent.

What you’ll add: place-search tools, the venue scout, and instructions for FieldTrip to hand over the research. The scout cannot see the chat, so the handover must include everything it needs.

Under the hood: how the scout gets its task

useSubagent makes the built-in task tool available to the parent agent. The scout runs with a fresh context: it has no separate URL, conversation ID, saved state, or access to the parent’s chat. Its task prompt is the complete briefing, and only its final answer returns to FieldTrip. Give it only the summary tool needed for that task.

Create src/tools/wikipedia.ts for finding nearby places and reading their Wikipedia summaries:

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

src/tools/wikipedia.ts
import { defineTool } from '@flue/runtime';
import * as v from 'valibot';
// Wikipedia APIs: free, no API key, but a descriptive User-Agent is required.
// https://www.mediawiki.org/wiki/API:Etiquette
const HEADERS = {
'User-Agent': 'FieldTripAgent/0.1 (Flue workshop demo; https://github.com/omkarkhair/field-trip-agent)',
Accept: 'application/json',
};
export const findNearbyPlaces = defineTool({
name: 'find_nearby_places',
description:
'List Wikipedia articles about places near a latitude/longitude (up to 10 km), with a one-line description and distance. Results include noise (stations, offices, events): pick the places that suit a group offsite.',
input: v.object({
latitude: v.number(),
longitude: v.number(),
radiusMeters: v.optional(v.pipe(v.number(), v.minValue(100), v.maxValue(10000)), 10000),
}),
async run({ data, signal }) {
const coord = `${data.latitude}|${data.longitude}`;
const params = new URLSearchParams({
action: 'query',
generator: 'geosearch',
ggscoord: coord,
ggsradius: String(Math.round(data.radiusMeters)),
ggslimit: '20',
prop: 'description|coordinates',
codistancefrompoint: coord,
colimit: 'max', // default is 10, which would leave half the results without a distance
format: 'json',
formatversion: '2',
});
const res = await fetch(`https://en.wikipedia.org/w/api.php?${params}`, { headers: HEADERS, signal });
if (!res.ok) throw new Error(`Wikipedia geosearch failed: HTTP ${res.status}`);
const body = (await res.json()) as {
query?: {
pages: Array<{ title: string; description?: string; coordinates?: Array<{ dist: number }> }>;
};
};
const pages = body.query?.pages ?? [];
if (pages.length === 0) throw new Error('No Wikipedia places found here. Try a larger radius or check the coordinates.');
return {
output: pages
.map((p) => ({
title: p.title,
description: p.description ?? '',
distanceM: Math.round(p.coordinates?.[0]?.dist ?? 0),
}))
.sort((a, b) => a.distanceM - b.distanceM),
};
},
});
export const getPlaceSummary = defineTool({
name: 'get_place_summary',
description:
'Get a short Wikipedia summary and URL for one place, by its exact article title (as returned by find_nearby_places).',
input: v.object({
title: v.pipe(v.string(), v.minLength(1)),
}),
async run({ data, signal }) {
const slug = encodeURIComponent(data.title.replaceAll(' ', '_'));
const res = await fetch(`https://en.wikipedia.org/api/rest_v1/page/summary/${slug}`, { headers: HEADERS, signal });
if (res.status === 404) throw new Error(`No Wikipedia article titled "${data.title}". Use a title from find_nearby_places.`);
if (!res.ok) throw new Error(`Wikipedia summary failed: HTTP ${res.status}`);
const page = (await res.json()) as {
title: string;
description?: string;
extract?: string;
content_urls?: { desktop?: { page?: string } };
};
return {
output: {
title: page.title,
description: page.description ?? '',
// Keep tool output small: it goes into the model's context window.
summary: (page.extract ?? '').slice(0, 600),
url: page.content_urls?.desktop?.page ?? `https://en.wikipedia.org/wiki/${slug}`,
},
};
},
});

Create src/subagents/venue-scout.ts to describe the scout’s research job and give it access to the place-summary tool:

  • src
    • subagents
      • venue-scout.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.

src/subagents/venue-scout.ts
// An ordinary module, NOT 'use agent': a subagent is a capability of the agent
// that mounts it, not a registered agent. It has no URL, no conversation id,
// no persistent state, and no useModel(). defineSubagent selects its model;
// omit that option to inherit the parent's model.
import { defineSubagent, useTool } from '@flue/runtime';
import { getPlaceSummary } from '../tools/wikipedia.ts';
function VenueScout() {
// The scout's world is only what it mounts here. The parent's tools,
// instructions, conversation and state are NOT inherited.
useTool(getPlaceSummary);
return `You are venue-scout. You assess a few places for a team offsite.
You only see the task prompt, not the user's conversation. The prompt gives you up to 3 places (Wikipedia article titles) and details about the group.
1. Call \`get_place_summary\` for every place, all in one batch.
2. Then write your final answer. Use facts from the summary; you may add general knowledge, but mark estimates as estimates.
Your final answer is all the parent sees. Always finish with this exact format, one block per place, and nothing else:
**<place name>** (<Wikipedia URL>)
- What to do: <1–2 activities for a group>
- Typical visit: <e.g. ~1–2 h> (estimate)
- Weather: <indoor | outdoor | mixed>; <how rain or heat affects the visit>
- Group fit: <one sentence about this group size and interests>`;
}
export const venueScout = defineSubagent({
name: 'venue-scout',
description:
'Assesses up to 3 places for a team offsite: activities, typical visit length, weather dependency, and group fit. Prompt with the exact Wikipedia titles, the city, the headcount, and the interests.',
agent: VenueScout,
model: 'cloudflare/@cf/meta/llama-4-scout-17b-16e-instruct',
});

Update src/agents/field-trip.ts to give it nearby-place search and the venue scout. The new instructions tell FieldTrip what to include in the research brief and how to use the scout’s report:

  • 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.

src/agents/field-trip.ts
'use agent';
import { useModel, usePersistentState, useSubagent, useTool } from '@flue/runtime';
import * as v from 'valibot';
import { geocodeCity, getForecast } from '../tools/weather.ts';
import { findNearbyPlaces } from '../tools/wikipedia.ts';
import { venueScout } from '../subagents/venue-scout.ts';
// The trip brief the agent remembers for this conversation.
type TripBrief = {
city?: string;
startDate?: string; // YYYY-MM-DD
endDate?: string; // YYYY-MM-DD
headcount?: number;
budget?: string;
interests?: string[];
};
export function FieldTrip() {
useModel('cloudflare/@cf/google/gemma-4-26b-a4b-it');
// Durable, per-conversation state (stored in this conversation's Durable Object).
// Shaped like React's useState, but it survives restarts and redeploys.
const [brief, setBrief] = usePersistentState<TripBrief>('brief', {});
// 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.',
input: v.object({
city: v.optional(v.string()),
startDate: v.optional(v.pipe(v.string(), v.isoDate())),
endDate: v.optional(v.pipe(v.string(), v.isoDate())),
headcount: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
budget: v.optional(v.string()),
interests: v.optional(v.array(v.string())),
}),
async run({ data }) {
const updates = Object.fromEntries(
Object.entries(data).filter(([, value]) => value !== undefined),
) as TripBrief;
setBrief((previous) => ({ ...previous, ...updates }));
return { output: { saved: updates } };
},
});
// Tools that call an external API (Open-Meteo), defined in src/tools/weather.ts.
useTool(geocodeCity);
useTool(getForecast);
// The parent finds candidate places (Wikipedia geosearch)...
useTool(findNearbyPlaces);
// ...and delegates all three candidates in one task. The scout runs in a
// fresh context with its own tools, and only its final answer comes back.
useSubagent(venueScout);
// 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. 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. For venue, activity or place suggestions:
a. Call \`geocode_city\`, then \`find_nearby_places\` with its coordinates.
b. Pick the 3 places that best fit the brief (skip stations, offices, hospitals, embassies, companies, events).
c. Call \`task\` ONCE with agent \`venue-scout\` for all 3 places. The scout cannot see this conversation, so the prompt must be a complete briefing: the exact place titles, the city, the headcount, and the interests.
d. Combine the results into a short plan, keeping the links. If you know the forecast, suggest outdoor places for dry days and indoor ones for rainy days.
5. Keep replies short: at most 120 words unless the user asks for more detail.
Today is ${today}.
## Saved trip brief
${hasBrief ? JSON.stringify(brief, null, 2) : '(nothing saved yet)'}`;
}

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

Terminal window
npm run deploy
sleep 5
npm run smoke -- https://field-trip-agent.<subdomain>.workers.dev cp4-live "Offsite in Lisbon from <START> to <END> for 14 people, budget 400 EUR each. We like food, history and the outdoors."
TIMEOUT_S=200 npm run smoke -- https://field-trip-agent.<subdomain>.workers.dev cp4-live "Suggest 3 places for our offsite."

Look for geocode_city, find_nearby_places, then one task call for venue-scout. The model may also call get_forecast. The task prompt must name three exact titles plus the city, headcount, and interests.

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

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

Verification gate

Prove it works

  • FieldTrip finds nearby places using Wikipedia.
  • One task call briefs venue-scout on all three places.
  • The scout returns an assessment of each place.
  • FieldTrip combines the research into a short plan with source links.
Optional mini quizCheck your understanding: briefing the scout3 questions instant feedback
1What can the scout read when it starts researching?
2How is the work divided?
3What does the scout send back to FieldTrip?
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/3-api-tools, 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/3-api-tools
npm ci
Option 02

Catch up with the room

Jump to cp/4-subagent, then use this checkpoint's 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/4-subagent
npm ci

Next: Give FieldTrip a workspace for the itinerary →