Service hooks
Service hooks run around the send loop and its individual provider rounds. This example retries a yes/no answer until it contains one of the accepted words, or until three attempts have run.
import type { ChatService } from '@johannes.latzel/llm-chat';
// Supply a ChatService from a provider package, or subclass ChatService.
declare const service: ChatService;
service.chat()
.system()
.child('general')
.prompt('rules')
.setContent('Answer yes/no questions with exactly one word: yes or no.');
let attempts = 0;
service.hook()
.beforeSendLoop()
.do(() => console.error('[service] loop start'));
service.hook()
.beforeSend()
.do(() => {
attempts += 1;
console.error(`[service] attempt ${attempts}`);
});
service.hook()
.afterSend()
.do(async () => {
const answer = service.lastAssistantContent()?.trim().toLowerCase();
if (answer === 'yes' || answer === 'no') return;
if (attempts >= 3) return;
await service.queue().user('Reply with exactly one word: yes or no.');
service.setNeedsResend();
});
service.hook()
.afterSendLoop()
.do(() => console.error(`[service] loop end after ${attempts} attempts`));
await service.chat().user('Is the sky blue?');
await service.send();
console.log(service.lastAssistantContent());
What happens
beforeSendLoopfires once persend(), before the retry loop.beforeSendfires once per provider round.afterSendvalidates the answer. A rejected answer queues a correction and callssetNeedsResend(), so the next loop iteration drains the queue and sends again.afterSendLoopfires once after the retry loop exits.- The attempt cap stops the loop when the model never produces the target format.