diff --git a/server/src/nest/assistant/assistant-tool-offer.ts b/server/src/nest/assistant/assistant-tool-offer.ts index 2225db6d8..6d48be1aa 100644 --- a/server/src/nest/assistant/assistant-tool-offer.ts +++ b/server/src/nest/assistant/assistant-tool-offer.ts @@ -11,9 +11,10 @@ import { PACKAGE_HELD_READS, PACKAGE_TOOL_CONTROLLERS } from './cards/registry'; * annotated read-only runs at once, every other one waits as a change card. * * Offering all of them in every step would cost a lot of tokens and runs past - * what some providers take in one request, so a turn starts with the core of - * a trip (days, places, bookings, packing, to-dos, budget, weather, search) - * and the model loads an addon's tools when it needs them (USE_TOOLS_TOOL). + * what some providers take in one request (MAX_OFFERED_TOOLS), so a turn + * starts with the core of a trip (days, places, the plan, weather, search) + * and the model loads the rest of the trip and the addons when it needs them + * (USE_TOOLS_TOOL). */ /** @@ -286,7 +287,14 @@ export function checkDenylist(names: Iterable): string[] { return problems; } -type ToolGroups = Readonly>; +interface ToolGroup { + about: string; + controllers: readonly string[]; + /** A part of the trip itself rather than of the rest of TREK: its changes carry no place in TREK of their own. */ + tripPart?: true; +} + +type ToolGroups = Readonly>; /** * The tool groups a turn can load, by the MCP controller that registers the @@ -295,6 +303,30 @@ type ToolGroups = Readonly controllers.map((controller) => [controller, group] as const), @@ -428,7 +465,8 @@ function useToolsDescription(core: string): string { Object.entries(ASSISTANT_TOOL_GROUPS) .map(([group, { about }]) => `"${group}" (${about})`) .join('; ') + - `. ${core}` + `. ${core} Only so many tools fit in one step: loading a group can unload the one used longest ago, ` + + 'which comes back when you call one of its tools.' ); } @@ -449,8 +487,7 @@ const USE_TOOLS_PARAMETERS: AiToolSpec['parameters'] = { export const HOME_USE_TOOLS_SPEC: AiToolSpec = { name: USE_TOOLS_TOOL, description: useToolsDescription( - 'Reading the trips (list_trips, and a trip by its id: days, places, bookings, packing, to-dos, budget, weather) ' + - 'needs nothing loaded.', + 'Reading the trips (list_trips, and a trip by its id: days, places, costs, weather) needs nothing loaded.', ), parameters: USE_TOOLS_PARAMETERS, }; @@ -458,7 +495,7 @@ export const HOME_USE_TOOLS_SPEC: AiToolSpec = { export const USE_TOOLS_SPEC: AiToolSpec = { name: USE_TOOLS_TOOL, description: useToolsDescription( - 'The trip itself (days, places, bookings, packing, to-dos, budget, weather, search) needs nothing loaded.', + 'The trip itself (days, places, the plan, notes, costs, weather, search) needs nothing loaded.', ), parameters: { type: 'object', diff --git a/server/src/nest/assistant/assistant-tools.constants.ts b/server/src/nest/assistant/assistant-tools.constants.ts index bf0ede495..0d1075fdb 100644 --- a/server/src/nest/assistant/assistant-tools.constants.ts +++ b/server/src/nest/assistant/assistant-tools.constants.ts @@ -19,6 +19,12 @@ export const MAX_READS_PER_STEP = 30; /** Answer cards one step shows; the reads past it answer the model as usual, without a card. */ export const MAX_CARDS_PER_STEP = 12; +/** + * The most tools one request offers the model: OpenAI's APIs and Azure refuse + * a longer list (`array_above_max_length`), whatever else the provider takes. + */ +export const MAX_OFFERED_TOOLS = 128; + /** What a tool answer may cost the conversation, as JSON text, after it was cut down to its structure. */ export const MAX_TOOL_OUTPUT_CHARS = 40_000; diff --git a/server/src/nest/assistant/assistant-tools.service.ts b/server/src/nest/assistant/assistant-tools.service.ts index d964b309b..1ceece5cc 100644 --- a/server/src/nest/assistant/assistant-tools.service.ts +++ b/server/src/nest/assistant/assistant-tools.service.ts @@ -31,6 +31,7 @@ import { HOME_USE_TOOLS_SPEC, isOfferedTool, isStudioController, + isTripPart, JOURNEY_PINNED_ARG, keptAtHome, USE_TOOLS_SPEC, @@ -39,6 +40,7 @@ import { import { ASSISTANT_SCOPES, ASSISTANT_SERVER_TOOLS, + MAX_OFFERED_TOOLS, PINNED_ARG, PREVIEW_BOOK_PAGE_TOOL, REMEMBER_TOOL, @@ -82,6 +84,8 @@ export interface ToolHint { destructive: boolean; creates: boolean; group: string | null; + /** The group is a part of the trip itself (its bookings, its packing), not a place elsewhere in TREK. */ + tripPart?: true; } interface ListedTool { @@ -218,6 +222,15 @@ function modelSchema(name: string, schema: Record, pinArg: stri return { ...rest, properties, ...(required.length > 0 ? { required } : {}) }; } +function hintOf(annotations: { destructiveHint?: boolean; idempotentHint?: boolean }, group: string | null): ToolHint { + return { + destructive: annotations.destructiveHint === true, + creates: annotations.idempotentHint === false, + group, + ...(group && isTripPart(group) ? { tripPart: true as const } : {}), + }; +} + function readResult(result: unknown): ToolRun { const record = (result ?? {}) as { content?: unknown; isError?: unknown }; const text = Array.isArray(record.content) @@ -264,7 +277,7 @@ export class AssistantToolSession { private readonly pinArg: string = PINNED_ARG, ) {} - /** The groups this turn loaded; the core is always there. */ + /** The groups this turn loaded, the one used longest ago first; the core is always there. */ private readonly loaded = new Set(); /** Reads the model called before their group was loaded in this turn, by name, with that group; told once. */ @@ -286,6 +299,10 @@ export class AssistantToolSession { specs(): AiToolSpec[] { // The step these specs go to sees every loaded group's schema. this.unoffered.clear(); + return this.offeredSpecs(); + } + + private offeredSpecs(): AiToolSpec[] { const listed = [...this.tools.values()] .filter((tool) => tool.offered) .filter((tool) => !this.grouped || tool.hint.group === null || this.loaded.has(tool.hint.group)) @@ -345,7 +362,7 @@ export class AssistantToolSession { // name from an earlier turn), so it wrote the arguments without the // schema (#2967). Its group is loaded here, so the next step offers the // schema. - this.loaded.add(unloaded); + this.use([unloaded]); this.unoffered.add(unloaded); } const group = this.tools.get(name)?.hint.group; @@ -382,6 +399,8 @@ export class AssistantToolSession { if (name === OPEN_JOURNEY_CHAT_TOOL && this.offersJournalChat) { return openJourneyChat(args, await this.invoke(OPEN_JOURNEY_CHAT_READ, {})); } + const group = this.tools.get(name)?.hint.group; + if (group && this.loaded.delete(group)) this.loaded.add(group); const final = name === TRANSIT_CREATE_TOOL ? await this.withFoundItinerary(args) : args; const run = await this.invoke(name, final); this.audit(name); @@ -436,9 +455,54 @@ ${hint}`, const groups = asked.filter((group) => group in ASSISTANT_TOOL_GROUPS); if (groups.length === 0) return { ok: false, value: `Name one of: ${Object.keys(ASSISTANT_TOOL_GROUPS).join(', ')}` }; - for (const group of groups) this.loaded.add(group); - const tools = [...this.tools.values()].filter((tool) => tool.hint.group && groups.includes(tool.hint.group)); - return { ok: true, value: { loaded: groups, tools: tools.map((tool) => tool.name) } }; + const { unloaded, refused } = this.use(groups); + const loaded = groups.filter((group) => !refused.includes(group)); + const tools = [...this.tools.values()].filter((tool) => tool.hint.group && loaded.includes(tool.hint.group)); + return { + ok: true, + value: { + loaded, + tools: tools.map((tool) => tool.name), + ...(unloaded.length > 0 ? { unloaded } : {}), + ...(refused.length > 0 + ? { + notLoaded: refused, + note: 'Too many tools for one step: load these on their own once the others are done.', + } + : {}), + }, + }; + } + + /** + * Loads groups as the ones used last, then unloads the ones used longest + * ago until the step offers no more than MAX_OFFERED_TOOLS. Groups asked for + * together that do not fit even alone are left out from the last one asked. + */ + private use(groups: readonly string[]): { unloaded: string[]; refused: string[] } { + for (const group of groups) { + this.loaded.delete(group); + this.loaded.add(group); + } + const unloaded: string[] = []; + const refused: string[] = []; + const drop = (group: string) => { + this.loaded.delete(group); + this.unoffered.delete(group); + }; + while (this.offeredSpecs().length > MAX_OFFERED_TOOLS) { + const oldest = [...this.loaded].find((group) => !groups.includes(group)); + if (oldest) { + drop(oldest); + unloaded.push(oldest); + continue; + } + const last = [...this.loaded].reverse().find((group) => groups.includes(group) && !refused.includes(group)); + if (!last || this.loaded.size === 1) break; + drop(last); + refused.push(last); + } + return { unloaded, refused }; } async close(): Promise { @@ -620,11 +684,7 @@ export class AssistantToolsService implements OnApplicationBootstrap { inputSchema, kind, pinned: pinNamesOf(pin.arg).some((key) => key in properties), - hint: { - destructive: annotations.destructiveHint === true, - creates: annotations.idempotentHint === false, - group: entry ? groupOf(entry) : null, - }, + hint: hintOf(annotations, entry ? groupOf(entry) : null), offered: true, }; if (offer.keep(listed)) tools.set(tool.name, { ...listed, offered: offer.offered?.(listed) ?? true }); diff --git a/server/src/nest/assistant/assistant.prompt.ts b/server/src/nest/assistant/assistant.prompt.ts index bbe124799..a8b7bf4ba 100644 --- a/server/src/nest/assistant/assistant.prompt.ts +++ b/server/src/nest/assistant/assistant.prompt.ts @@ -29,7 +29,7 @@ How you work: - The trip card may start with what the user is asking about. A question about "this place", "it" or "here" is about that; never ask which place they mean then. - The user can name days, places and bookings with "@" before the name. The trip card then lists what they named, with the ids; use those. - The app shows the places your searches find as cards with a picture, and the weather you look up as a strip. Do not list them again in your text; say in a sentence or two which ones you suggest and why. -- Besides the open trip you can work in the rest of TREK: tours (hikes, bike tours, city walks), the road trip, the travel journal, the vacation planner, the atlas, collections, the trip's chat, polls and notes, files and the user's settings. Their tools are not loaded at first: call use_addon_tools with the groups you need, then use them in the same reply. Tools without a trip work on the user's own data across trips. +- Besides the open trip you can work in the rest of TREK: tours (hikes, bike tours, city walks), the road trip, the travel journal, the vacation planner, the atlas, collections, the trip's chat, polls and notes, files and the user's settings. Their tools are not loaded at first, and neither are those of the trip's bookings, its packing lists and to-dos, changes to its budget and its tags: call use_addon_tools with the groups you need, then use them in the same reply. Tools without a trip work on the user's own data across trips. - Propose a deletion only when the user asks for it; it cannot be undone, and the card says so. - You cannot share, invite people, publish links or calendar feeds, change who can see a trip, leave, copy or delete the trip, or make a new one. If asked, say so in one sentence and where in TREK the user can do it. - Keep what will matter later with remember_for_trip on your own, without asking: who travels, needs, likes and dislikes, budget, pace, fixed times the user mentions, and anything they ask you to remember. It is kept at once and comes back as in every later conversation; say briefly that you noted it. Where you are not sure it lasts, offer it as a follow-up instead ("Remember: …"). Never say you cannot remember things. diff --git a/server/src/nest/assistant/tool-call-generic.helpers.ts b/server/src/nest/assistant/tool-call-generic.helpers.ts index 5c9a8e4ef..7fdcee4bf 100644 --- a/server/src/nest/assistant/tool-call-generic.helpers.ts +++ b/server/src/nest/assistant/tool-call-generic.helpers.ts @@ -205,6 +205,6 @@ export function describeGeneric( undoable: false, effect: null, tool: toolName, - ...(hint?.group ? { domain: hint.group } : {}), + ...(hint?.group && !hint.tripPart ? { domain: hint.group } : {}), }; } diff --git a/server/tests/unit/nest/assistant/assistant-tool-cap.test.ts b/server/tests/unit/nest/assistant/assistant-tool-cap.test.ts new file mode 100644 index 000000000..592b8b730 --- /dev/null +++ b/server/tests/unit/nest/assistant/assistant-tool-cap.test.ts @@ -0,0 +1,150 @@ +/** + * The tools one request offers the model stay within what OpenAI's APIs and + * Azure take (MAX_OFFERED_TOOLS): a longer list is refused before the model + * reads a word, with `array_above_max_length` (a trip chat on Azure Foundry + * offered 130 in its first step). + */ +import { ADDON_IDS } from '../../../../src/addons'; +import { ASSISTANT_TOOL_GROUPS } from '../../../../src/nest/assistant/assistant-tool-offer'; +import { MAX_OFFERED_TOOLS } from '../../../../src/nest/assistant/assistant-tools.constants'; +import { + AssistantToolsService, + type AssistantToolSession, +} from '../../../../src/nest/assistant/assistant-tools.service'; +import { makeJourney } from '../../../helpers/factories/journeys'; +import { setAddonEnabled, setAppSetting } from '../../../helpers/factories/settings'; +import { makeTrip } from '../../../helpers/factories/trips'; +import { makeUser } from '../../../helpers/factories/users'; +import { FakeRealtimeService } from '../../../helpers/fake-realtime'; +import { bootTestApp } from '../../../helpers/test-app'; +import { MikroORM } from '@mikro-orm/core'; + +import { beforeAll, describe, expect, it } from 'vitest'; + +let orm: MikroORM; +let tools: AssistantToolsService; + +const GROUPS = Object.keys(ASSISTANT_TOOL_GROUPS); + +beforeAll(async () => { + const app = await bootTestApp(new FakeRealtimeService()); + orm = app.get(MikroORM); + tools = app.get(AssistantToolsService); + // Every addon on, so every group holds all it can. + for (const addon of Object.values(ADDON_IDS)) await setAddonEnabled(orm, addon, true); + await setAppSetting(orm, 'tours_wanderer_enabled', 'true'); +}); + +async function tripSession(): Promise { + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id, { title: 'Kyoto' }); + return tools.open(user.id, trip.id); +} + +const names = (session: AssistantToolSession) => session.specs().map((spec) => spec.name); + +describe('the tools one step offers', () => { + it('ASTCAP-001: a trip chat starts within the limit, with room for any one group beside the core', async () => { + const session = await tripSession(); + try { + expect(session.specs().length).toBeLessThanOrEqual(MAX_OFFERED_TOOLS); + for (const group of GROUPS) { + const one = await tripSession(); + try { + const run = await one.call('use_addon_tools', { groups: [group] }); + expect(run.ok, group).toBe(true); + expect((run.value as { loaded: string[] }).loaded, group).toEqual([group]); + expect(one.specs().length, group).toBeLessThanOrEqual(MAX_OFFERED_TOOLS); + } finally { + await one.close(); + } + } + } finally { + await session.close(); + } + }); + + it('ASTCAP-002: loading one group after another unloads the one used longest ago, never the one just asked for', async () => { + const session = await tripSession(); + try { + const unloadedSeen: string[] = []; + for (const group of GROUPS) { + const run = await session.call('use_addon_tools', { groups: [group] }); + const value = run.value as { loaded: string[]; tools: string[]; unloaded?: string[] }; + expect(value.loaded).toEqual([group]); + expect(value.unloaded ?? [], group).not.toContain(group); + unloadedSeen.push(...(value.unloaded ?? [])); + const offered = names(session); + expect(offered.length, group).toBeLessThanOrEqual(MAX_OFFERED_TOOLS); + for (const tool of value.tools) expect(offered, `${group}: ${tool}`).toContain(tool); + } + // Every group cannot fit at once, so the walk had to make room, oldest first. + expect(unloadedSeen.length).toBeGreaterThan(0); + expect(unloadedSeen[0]).toBe(GROUPS[0]); + } finally { + await session.close(); + } + }); + + it('ASTCAP-003: asking for every group at once loads what fits and names the rest', async () => { + const session = await tripSession(); + try { + const run = await session.call('use_addon_tools', { groups: GROUPS }); + const value = run.value as { loaded: string[]; notLoaded?: string[]; note?: string }; + expect(session.specs().length).toBeLessThanOrEqual(MAX_OFFERED_TOOLS); + expect(value.loaded.length).toBeGreaterThan(0); + expect([...value.loaded, ...(value.notLoaded ?? [])].sort()).toEqual([...GROUPS].sort()); + expect(value.notLoaded?.length ?? 0).toBeGreaterThan(0); + expect(value.note).toMatch(/on their own/); + } finally { + await session.close(); + } + }); + + it('ASTCAP-004: a tool of a group that was unloaded loads it again when the model calls it', async () => { + const session = await tripSession(); + try { + const first = GROUPS[0]!; + const run = await session.call('use_addon_tools', { groups: [first] }); + const tool = (run.value as { tools: string[] }).tools[0]!; + // Load the others until the first one is gone again. + for (const group of GROUPS.slice(1)) { + await session.call('use_addon_tools', { groups: [group] }); + if (!names(session).includes(tool)) break; + } + expect(names(session)).not.toContain(tool); + expect(session.pinArgs(tool, {})).not.toHaveProperty('error'); + expect(names(session)).toContain(tool); + expect(session.specs().length).toBeLessThanOrEqual(MAX_OFFERED_TOOLS); + } finally { + await session.close(); + } + }); + + it('ASTCAP-005: the home chat stays within the limit with any one group loaded', async () => { + const { user } = await makeUser(orm); + for (const group of GROUPS) { + const session = await tools.openHome(user.id); + try { + expect(session.specs().length, 'home').toBeLessThanOrEqual(MAX_OFFERED_TOOLS); + await session.call('use_addon_tools', { groups: [group] }); + expect(session.specs().length, group).toBeLessThanOrEqual(MAX_OFFERED_TOOLS); + } finally { + await session.close(); + } + } + }); + + it('ASTCAP-006: a journey chat offers no more than the limit on either of its pages', async () => { + const { user } = await makeUser(orm); + const journey = await makeJourney(orm, user.id, { title: 'Lisbon' }); + for (const surface of ['studio', 'journal'] as const) { + const session = await tools.openJourney(user.id, journey.id, { role: 'owner', surface }); + try { + expect(session.specs().length, surface).toBeLessThanOrEqual(MAX_OFFERED_TOOLS); + } finally { + await session.close(); + } + } + }); +}); diff --git a/server/tests/unit/nest/assistant/tool-call-preview.helpers.test.ts b/server/tests/unit/nest/assistant/tool-call-preview.helpers.test.ts index e58af2d05..44b97a6fe 100644 --- a/server/tests/unit/nest/assistant/tool-call-preview.helpers.test.ts +++ b/server/tests/unit/nest/assistant/tool-call-preview.helpers.test.ts @@ -226,6 +226,18 @@ describe('describeToolCall', () => { const year = describeToolCall('add_vacay_year', 'tc-9', { year: 2027 }, hinted(false, true, 'vacay')); expect(year).toMatchObject({ verbKey: 'genericCreate', domain: 'vacay', undoable: false }); // A vacation day has a card of its own, even before its lookup ran: the day, in the vacation planner. + // A part of the trip that loads as a group (its tags) is no place elsewhere in TREK: no domain. + const tag = describeToolCall( + 'add_trip_label', + 'tc-11', + { name: 'Food' }, + { + ...ctx, + hintOf: () => ({ destructive: false, creates: true, group: 'tags', tripPart: true as const }), + }, + ); + expect(tag).toMatchObject({ verbKey: 'genericCreate', tool: 'add_trip_label' }); + expect(tag).not.toHaveProperty('domain'); const vacay = describeToolCall('toggle_vacay_entry', 'tc-10', { date: '2026-07-01', half: true }, ctx); expect(vacay).toMatchObject({ verbKey: 'addVacationDay', subject: 'Wed 1 Jul', domain: 'vacay', undoable: false }); expect(vacay.rows).toEqual([]);