Agent Handoffs
medium10 minhandoffs.ts
A front-desk agent should route each customer to the right specialist — billing or tech support — and let that specialist answer.
What it shows
- List specialists in
handoffson the triage agent - Follow the route with
onHandoffand readresult.finalAgent
The code
handoffs.ts
import { Agent, Cogitator, tool } from '@cogitator-ai/core';
import { z } from 'zod';
const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');
const invoices: Record<string, { amount: number; status: 'paid' | 'due' }> = {
'INV-204': { amount: 129, status: 'due' },
};
const lookupInvoice = tool({
name: 'lookup_invoice',
description: 'Look up an invoice by its number.',
parameters: z.object({ invoice: z.string().describe('Invoice number, e.g. "INV-204"') }),
execute: async ({ invoice }) => invoices[invoice] ?? { error: `No invoice ${invoice}` },
});
const serviceStatus = tool({
name: 'service_status',
description: 'Current status of the service and known incidents.',
parameters: z.object({}),
execute: async () => ({ status: 'degraded', incident: 'Login emails are delayed by ~10 minutes' }),
});
const cog = new Cogitator({
llm: { providers: { google: { apiKey } } },
memory: { adapter: 'memory' },
});
const billing = new Agent({
name: 'billing',
description: 'Invoices, payments and refunds',
model: 'google/gemini-3.5-flash-lite',
instructions: 'You are the billing specialist. Use lookup_invoice. Answer in two sentences at most.',
tools: [lookupInvoice],
});
const techSupport = new Agent({
name: 'tech_support',
description: 'Login problems, outages and bugs',
model: 'google/gemini-3.5-flash-lite',
instructions: 'You are technical support. Check service_status first. Answer in two sentences at most.',
tools: [serviceStatus],
});
const triage = new Agent({
name: 'triage',
model: 'google/gemini-3.5-flash-lite',
instructions:
'You greet customers and hand the conversation over to the right specialist. Never answer billing or technical questions yourself.',
handoffs: [billing, techSupport],
temperature: 0,
});
for (const input of [
'How much do I owe on invoice INV-204?',
"I can't log in, the email with the code never arrives.",
]) {
const result = await cog.run(triage, {
input,
onHandoff: ({ from, to, reason }) => console.log(`${from} -> ${to}${reason ? ` (${reason})` : ''}`),
});
console.log(`${result.finalAgent ?? 'triage'}: ${result.output}`);
}
await cog.close();Run it
install · bash
pnpm add @cogitator-ai/core zodEnvironment
GOOGLE_API_KEYrun · bash
GOOGLE_API_KEY=your-key npx tsx handoffs.tsOr run the full example from a clone of the repository (keys in .env):
repository · bash
npx tsx examples/core/15-handoffs.ts