Skip to content

AbstractGadget

Defined in: gadgets/gadget.ts:187

Abstract base class for gadgets. Most users should use the Gadget() factory or createGadget() function instead, as they provide better type safety and simpler APIs.

Extend this class directly only when you need advanced control over gadget behavior.

new AbstractGadget(): AbstractGadget

AbstractGadget

abstract description: string

Defined in: gadgets/gadget.ts:197

Human-readable description of what the gadget does.


optional examples: GadgetExample<unknown>[]

Defined in: gadgets/gadget.ts:221

Optional usage examples to help LLMs understand proper invocation. Examples are rendered in getInstruction() alongside the schema.

Note: Uses broader unknown type to allow typed examples from subclasses while maintaining runtime compatibility.


optional name: string

Defined in: gadgets/gadget.ts:192

The name of the gadget. Used for identification when LLM calls it. If not provided, defaults to the class name.


optional parameterSchema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Defined in: gadgets/gadget.ts:204

Optional Zod schema describing the expected input payload. When provided, it will be validated before execution and transformed into a JSON Schema representation that is surfaced to the LLM as part of the instructions.


optional timeoutMs: number

Defined in: gadgets/gadget.ts:212

Optional timeout in milliseconds for gadget execution. If execution exceeds this timeout, a TimeoutException will be thrown. If not set, the global defaultGadgetTimeoutMs from runtime options will be used. Set to 0 or undefined to disable timeout for this gadget.

get instruction(): string

Defined in: gadgets/gadget.ts:405

Auto-generated instruction text for the LLM. Combines name, description, and parameter schema into a formatted instruction.

string

createLinkedAbortController(ctx?): AbortController

Defined in: gadgets/gadget.ts:380

Create an AbortController linked to the execution context’s signal. When the parent signal aborts, the returned controller also aborts with the same reason.

Useful for passing abort signals to child operations like fetch() while still being able to abort them independently if needed.

ExecutionContext

The execution context containing the parent abort signal

AbortController

A new AbortController linked to the parent signal

class FetchGadget extends Gadget({
description: 'Fetches data from URL',
schema: z.object({ url: z.string() }),
}) {
async execute(params: this['params'], ctx?: ExecutionContext): Promise<string> {
const controller = this.createLinkedAbortController(ctx);
// fetch() will automatically abort when parent times out
const response = await fetch(params.url, { signal: controller.signal });
return response.text();
}
}

abstract execute(params, ctx?): GadgetExecuteReturn | Promise<GadgetExecuteReturn>

Defined in: gadgets/gadget.ts:256

Execute the gadget with the given parameters. Can be synchronous or asynchronous.

Record<string, unknown>

Parameters passed from the LLM

ExecutionContext

Optional execution context for cost reporting and LLM access

GadgetExecuteReturn | Promise<GadgetExecuteReturn>

Result as a string, or an object with result and optional cost

// Simple string return (free gadget)
execute(params) {
return "result";
}
// Object return with cost tracking
execute(params) {
return { result: "data", cost: 0.001 };
}
// Using context for callback-based cost reporting
execute(params, ctx) {
ctx.reportCost(0.001);
return "result";
}
// Using wrapped LLMist for automatic cost tracking
async execute(params, ctx) {
const summary = await ctx.llmist.complete('Summarize: ' + params.text);
return summary;
}

getInstruction(optionsOrArgPrefix?): string

Defined in: gadgets/gadget.ts:416

Generate instruction text for the LLM. Combines name, description, and parameter schema into a formatted instruction.

Optional custom prefixes for examples, or just argPrefix string for backwards compatibility

string | { argPrefix?: string; endPrefix?: string; startPrefix?: string; }

string

Formatted instruction string


onAbort(ctx, cleanup): void

Defined in: gadgets/gadget.ts:331

Register a cleanup function to run when execution is aborted (timeout or cancellation). The cleanup function is called immediately if the signal is already aborted. Errors thrown by the cleanup function are silently ignored.

Use this to clean up resources like browser instances, database connections, or child processes when the gadget is cancelled due to timeout.

The execution context containing the abort signal

ExecutionContext | undefined

() => void | Promise<void>

Function to run on abort (can be sync or async)

void

class BrowserGadget extends Gadget({
description: 'Fetches web page content',
schema: z.object({ url: z.string() }),
}) {
async execute(params: this['params'], ctx?: ExecutionContext): Promise<string> {
const browser = await chromium.launch();
this.onAbort(ctx, () => browser.close());
const page = await browser.newPage();
this.onAbort(ctx, () => page.close());
await page.goto(params.url);
const content = await page.content();
await browser.close();
return content;
}
}

throwIfAborted(ctx?): void

Defined in: gadgets/gadget.ts:292

Throws an AbortException if the execution has been aborted.

Call this at key checkpoints in long-running gadgets to allow early exit when the gadget has been cancelled (e.g., due to timeout). This enables resource cleanup and prevents unnecessary work after cancellation.

ExecutionContext

The execution context containing the abort signal

void

AbortException if ctx.signal.aborted is true

class DataProcessor extends Gadget({
description: 'Processes data in multiple steps',
schema: z.object({ items: z.array(z.string()) }),
}) {
async execute(params: this['params'], ctx?: ExecutionContext): Promise<string> {
const results: string[] = [];
for (const item of params.items) {
// Check before each expensive operation
this.throwIfAborted(ctx);
results.push(await this.processItem(item));
}
return results.join(', ');
}
}