AI ROUTER
ai-router.ts
Intent-based routing with fallback chains.
StarkWHAT THIS PATTERN TEACHES
How to map natural language input to typed intents and dispatch to handlers. Intents are a closed set defined upfront. Ambiguity routes to clarification, not a random handler.
WHEN TO USE THIS
Chatbots, command interpreters, natural language interfaces — any system that routes user input to actions.
AT A GLANCE
const intents = ['create_order', 'check_status', 'cancel'] as const;
async function route(input: string) {
const intent = await detectIntent(input, intents);
return handlers[intent](input);
}FRAMEWORK IMPLEMENTATIONS
TypeScript
const INTENTS = ['create_order', 'check_status', 'cancel', 'clarify'] as const;
type Intent = typeof INTENTS[number];
async function detectIntent(input: string): Promise<Intent> {
const result = await model.complete({
messages: [{ role: 'user', content: input }],
system: `Classify into: ${INTENTS.join(', ')}`,
});
const intent = parseIntent(result);
return INTENTS.includes(intent) ? intent : 'clarify';
}
const handlers: Record<Intent, (input: string) => Promise<Response>> = {
create_order: handleCreate,
check_status: handleStatus,
cancel: handleCancel,
clarify: handleClarify,
};