
Ax Gen
- 1 installs
- 5 repo stars
- Updated August 4, 2026
- evalops/kestrel
Generates correct AxGen code with @ax-llm/ax for generators, forward/streamingForward, assertions, field processors, step hooks, and structured outputs.
About
A codegen reference for building AxGen generators with @ax-llm/ax, covering the ax() factory, streaming, auto-retry assertions, step hooks, and multi-step output completion. A developer uses it when writing structured-output LLM generation code with ax.
- Prefers ax() factory and passing an ai() instance to forward()
- Covers streamingForward, auto-retry assertions, and multi-step stopping
Ax Gen by the numbers
- 1 all-time installs (skills.sh)
- Ranked #14,102 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/evalops/kestrel --skill ax-genAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 5 |
| Last updated | August 4, 2026 |
| Repository | evalops/kestrel ↗ |
What it does
Generates correct AxGen code with @ax-llm/ax for generators, forward/streamingForward, assertions, field processors, step hooks, and structured outputs.
Files
AxGen Codegen Rules (@ax-llm/ax)
Use this skill to generate AxGen code. Prefer short, modern, copyable patterns. Do not write tutorial prose unless the user explicitly asks for explanation.
Use These Defaults
- Use
ax(...)factory, notnew AxGen(...). - Always pass an AI instance from
ai(...)as the first argument toforward(). - Streaming uses
streamingForward(), notforward()with a stream option. - Assertions auto-retry with error feedback on failure.
- Step hook mutations are applied at the next step boundary (pending pattern).
stopFunctionaccepts a string or string[] for multiple stop functions.- Multi-step continues until: all outputs filled, stop function called, or
maxStepsreached.
Canonical Pattern
import { ai, ax, s } from '@ax-llm/ax';
const llm = ai({
name: 'openai',
apiKey: process.env.OPENAI_APIKEY!,
});
// Inline signature
const gen = ax('input:string -> output:string, reasoning:string');
// Reusable signature
const sig = s('question:string, context:string[] -> answer:string');
const gen2 = ax(sig);
// With options
const gen3 = ax('input -> output', {
description: 'A helpful assistant',
maxRetries: 3,
maxSteps: 10,
temperature: 0.7,
});
const result = await gen.forward(llm, { input: 'Hello world' });
console.log(result.output);Running AxGen
forward()
const result = await gen.forward(llm, { input: '...' });
// With options
const result = await gen.forward(llm, { input: '...' }, {
maxRetries: 5,
model: 'gpt-4.1',
modelConfig: { temperature: 0.9, maxTokens: 1000 },
debug: true,
});streamingForward()
const stream = gen.streamingForward(llm, { input: 'Write a long story' });
for await (const chunk of stream) {
if (chunk.delta.output) process.stdout.write(chunk.delta.output);
}Stopping And Cancellation
import { AxAIServiceAbortedError } from '@ax-llm/ax';
const timer = setTimeout(() => gen.stop(), 3_000);
try {
const result = await gen.forward(llm, { topic: 'Long document' }, {
abortSignal: AbortSignal.timeout(10_000),
});
} catch (err) {
if (err instanceof AxAIServiceAbortedError) console.log('Aborted');
}Rules:
gen.stop()gracefully stops multi-step execution at the next step boundary.abortSignalcancels the underlying AI service call immediately.- Catch
AxAIServiceAbortedErrorwhen using either mechanism.
Assertions And Validation
// Standard assertion (checked after forward completes)
gen.addAssert(
(args) => args.output.length > 50,
'Output must be at least 50 characters'
);
// Streaming assertion (checked during streaming)
gen.addStreamingAssert(
'output',
(text) => !text.includes('forbidden'),
'Output contains forbidden text'
);Rules:
- Failed assertions cause an automatic retry with the error message fed back to the LLM.
addAssertreceives the full output object.addStreamingAsserttargets a specific field and receives the partial text so far.
Field Processors
// Post-processing after generation
gen.addFieldProcessor('summary', (value, context) => value.toUpperCase());
// Streaming field processor (called on each chunk)
gen.addStreamingFieldProcessor('content', (partialValue, context) => {
console.log(`Received ${partialValue.length} chars`);
return partialValue;
});Rules:
addFieldProcessorruns once after the field is fully generated.addStreamingFieldProcessorruns on each streaming chunk for the target field.- Both must return the (possibly transformed) value.
Function Calling
const result = await gen.forward(llm, { question: '...' }, {
functions: tools,
functionCallMode: 'auto',
stopFunction: 'finalAnswer',
});Rules:
functionCallModecan be'auto','none', or a specific function name to force.stopFunctionaccepts a string or string[] to halt multi-step on specific function calls.- Multi-step continues until all outputs filled, stop function called, or
maxStepsreached.
Caching
Response Caching
const gen = ax('question:string -> answer:string', {
cachingFunction: async (key, value?) => {
if (value !== undefined) {
await cache.set(key, value);
return;
}
return await cache.get(key);
},
});Context Caching
const result = await gen.forward(llm, { question: '...' }, {
contextCache: { cacheBreakpoint: 'after-examples' },
});Rules:
cachingFunctionacts as a get/set: called with(key)to read,(key, value)to write.contextCacheenables AI provider-level prompt caching for long context.
Sampling And Result Picker
const result = await gen.forward(llm, { question: '...' }, {
sampleCount: 3,
resultPicker: async (samples) => {
// Evaluate each sample and return the index of the best one
return bestIndex;
},
});Rules:
sampleCountgenerates multiple completions in parallel.resultPickerreceives all samples and must return the index of the chosen result.
Extended Thinking
const result = await gen.forward(llm, { question: '...' }, {
thinkingTokenBudget: 'medium',
showThoughts: true,
});
console.log(result.thought);Rules:
thinkingTokenBudgetcan be'low','medium','high', or a number.- Set
showThoughts: trueto include the model's reasoning inresult.thought.
Step Hooks
const result = await gen.forward(llm, values, {
stepHooks: {
beforeStep: (ctx) => {
if (ctx.functionsExecuted.has('complexanalysis')) {
ctx.setModel('smart');
ctx.setThinkingBudget('high');
}
},
afterStep: (ctx) => {
console.log(`Usage: ${ctx.usage.totalTokens} tokens`);
},
},
});AxStepContext Read-Only Properties
stepIndex- current step numbermaxSteps- configured maximum stepsisFirstStep- whether this is the first stepfunctionsExecuted-Set<string>of function names called so farlastFunctionCalls- array of the most recent function call resultsusage- token usage statisticsstate- current step state
AxStepContext Mutators
setModel(model)- change the model for the next stepsetThinkingBudget(budget)- adjust thinking budgetsetTemperature(temp)- adjust temperaturesetMaxTokens(max)- adjust max output tokenssetOptions(opts)- set arbitrary forward optionsaddFunctions(fns)- add functions for the next stepremoveFunctions(names)- remove functions by namestop()- stop multi-step execution
Rules:
- All mutations are pending and applied at the next step boundary.
beforeStepruns before each LLM call;afterStepruns after.- Use
afterFunctionExecutionto react to specific function results.
Self-Tuning
// Simple: enable all self-tuning
const result = await gen.forward(llm, values, { selfTuning: true });
// Granular: pick what to tune
const result = await gen.forward(llm, values, {
selfTuning: {
model: true,
thinkingBudget: true,
functions: [searchWeb, calculate],
},
});Rules:
selfTuning: trueenables automatic model and parameter selection.- Granular config allows tuning specific aspects independently.
selfTuning.functionsprovides a pool of functions the tuner may add or remove per step.
Error Handling
import { AxGenerateError } from '@ax-llm/ax';
try {
const result = await gen.forward(llm, { input: '...' });
} catch (error) {
if (error instanceof AxGenerateError) {
console.log(error.details.model, error.details.signature);
}
}Rules:
AxGenerateErrorincludesdetailswithmodelandsignaturefor debugging.AxAIServiceAbortedErroris thrown on cancellation viastop()orabortSignal.
Examples
Fetch these for full working code:
- Streaming — streaming with assertions
- Assertions — output validation
- Streaming Assertions — streaming with assertion checks
- Structured Output — fluent API with validation
- Debug Logging — debug mode and step hooks
- Stop Function — stop functions
- Fibonacci — streaming with thinking
- Extraction — information extraction
- Multi-Sampling — sample count usage
Do Not Generate
- Do not use
new AxGen(...)for new code unless explicitly required. - Do not pass raw API keys or config objects where an
ai(...)instance is expected. - Do not use
forward()for streaming; usestreamingForward(). - Do not forget that assertions auto-retry; avoid manual retry loops around assertion logic.
- Do not mutate step hook context expecting immediate effect; mutations are pending until the next step.
- Do not assume multi-step stops after one LLM call; it continues until outputs are filled, a stop function fires, or
maxStepsis reached.