Stopping a request
Pass an AbortSignal as signal on a request to stop it, for example from a stop button, a timeout, or when a newer message arrives. The stop takes effect at once: also in the middle of a provider call, a rate limit wait, a tool, or a conversation summary.
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
for await (const chunk of toolpack.stream({ model, messages, signal: controller.signal })) {
if (chunk.finish_reason === 'aborted') break; // stopped: what arrived before is kept
process.stdout.write(chunk.delta);
}
What each call does on a stop
| Call | On a stop |
|---|---|
stream() | Ends without throwing. The last chunk is { delta: '', finish_reason: 'aborted' } |
generate() | Rejects with an AbortedError (name is 'AbortError', code is 'ABORTED') |
import { AbortedError } from 'toolpack-sdk';
try {
const response = await toolpack.generate({ model, messages, signal: controller.signal });
} catch (err) {
if (err instanceof AbortedError) return; // stopped by the caller, not a failure
throw err;
}
A stop is never reported as a provider error. Requests without a signal behave as if they can never be stopped.
Tools and the stop
- A tool that has not started when the stop arrives is not run
- The SDK stops waiting for a tool that is running, and for a pending human confirmation (
onToolConfirm) - Tools receive the signal as
ctx.signal, so a long-running tool can end its own work:
execute: async (args, ctx) => {
const res = await fetch(args.url, { signal: ctx.signal });
return await res.text();
}
A tool that does not read ctx.signal keeps running in the background after a stop, and its result is ignored. Tools in the same parallel batch all start together, so a stop only skips the ones that have not started.
Providers
The built-in providers pass the signal on to their own HTTP request, so the call is cancelled and not left running. A custom provider should pass request.signal to its HTTP client too. If it does not, the caller is still released at once, but the provider's request runs to its end in the background.
Helpers
| Export | What it does |
|---|---|
AbortedError | The error generate() rejects with on a stop. Extends SDKError |
raceAbort(promise, signal?) | Settles like promise, unless the signal is aborted first: then it rejects with an AbortedError |
untilAborted(source, signal?) | Yields what an async iterable yields, and ends quietly as soon as the signal is aborted |
Agents
Agent runs take the same signal (in AgentInput and AgentRunOptions). See Stopping Agents.