Install any skill in seconds. Free to start, no credit card required.
Get Started Free →This skill helps an LLM generate correct AxGen code using @ax-llm/ax. Use when the user asks about ax(), AxGen, generators, forward(), streamingForward(), validation, assertions, streaming assertions, field processors, step hooks, self-tuning, or structured outputs. For MCP clients, transports, prompts, resources, tasks, subscriptions, or authentication use ax-mcp alongside this skill.
.claude/skills/ax-llm-ax-gen/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 150% | 0% |
| case-02 | ✗→✓ | ▲ Improved | 189% | 0% |
| case-03 | ✗→✓ | ▲ Improved | 89% | 0% |
| case-04 | ✗→✓ | ▲ Improved | 319% | 0% |
| case-05 | ✗→✓ | ▲ Improved | 166% | 0% |
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 the ax-mcp skill when AxGen attaches native MCP clients or consumes MCP prompts, resources, tools, tasks, subscriptions, authentication, or events.
ax(...) factory, not new AxGen(...).ai(...) as the first argument to forward().streamingForward(), not forward() with a stream option.addAssert(...) for whole-output hard invariants with correction retries.addStreamingAssert(...) for partial streaming hard invariants with fail-fast per-attempt correction retries.bestOfN(...) / refine(...) for reward-scored complete outputs.stopFunction accepts a string or string] for multiple stop functions.maxSteps reached.typescriptimport { 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);
ax() accepts any signature built with f(), and f().input() / .output() accept Standard Schema v1 validators directly — per-field or a whole z.object({...}):
typescriptimport { z } from 'zod'; import { ax, f } from '@ax-llm/ax'; const gen = ax( f() .input(z.object({ productName: z.string(), buyerProfile: z.string(), })) .output(z.object({ headline: z.string(), recommendation: z.enum(['buy', 'wait', 'skip']), })) .build() );
Constraints (.min(), .email(), .regex()) and custom logic (.refine(), .transform(), .superRefine()) execute in the normal validation/retry pipeline — at parse time on complete field values, including at field boundaries during streaming. For cache/internal hints pass companion options: .input('ctx', z.string(), { cache: true }) or .output('reasoning', z.string(), { internal: true }).
Define tool functions with zod the same way — fn().arg() / .returns() accept per-argument or whole-object schemas and infer the handler's argument type:
typescriptimport { z } from 'zod'; import { ax, fn } from '@ax-llm/ax'; const lookupProduct = fn('lookupProduct') .description('Look up a product by name') .arg(z.object({ productName: z.string().min(1), includeSpecs: z.boolean().optional(), })) .returns(z.object({ price: z.number(), inStock: z.boolean(), rating: z.number().min(1).max(5), })) .handler(async ({ productName, includeSpecs }) => ({ price: 79.99, inStock: true, rating: 4.3, })) .build(); const result = await gen.forward(llm, { ... }, { functions: [lookupProduct] });
forward()typescriptconst result = await gen.forward(llm, { input: '...' }); // With options const result = await gen.forward(llm, { input: '...' }, { maxRetries: 5, model: 'gpt-5.4-mini', modelConfig: { temperature: 0.9, maxTokens: 1000 }, debug: true, });
AxGen respects axGlobals for app-wide runtime defaults:
typescriptimport { axGlobals } from '@ax-llm/ax'; import { trace } from '@opentelemetry/api'; const responseCache = new Map<string, any>(); axGlobals.rateLimiter = async (next, info) => next(); axGlobals.tracer = trace.getTracer('my-app'); axGlobals.debug = true; axGlobals.cachingFunction = async (key, value?) => { if (value !== undefined) { responseCache.set(key, value); return; } return responseCache.get(key); };
Rules:
rateLimiter, tracer, or meter is carried to every retry and provider call without being serialized or mutating the generator. Concurrent forwards remain isolated.abortSignal from axGlobals is merged with local forward signals.customLabels merge from globals to AI service to forward options.cachingFunction and functionResultFormatter also fall back to current axGlobals when local options do not provide them.streamingForward()typescriptconst 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); }
typescriptimport { 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.abortSignal cancels the underlying AI service call immediately.AxAIServiceAbortedError when using either mechanism.typescriptimport { ax, bestOfN, f } from '@ax-llm/ax'; import { z } from 'zod'; // Schema validation: output shape and field validity. const gen = ax( f() .input('topic', z.string().min(1)) .output('summary', z.string().min(50)) .build() ); // bestOfN: choose the best complete candidate. const selected = bestOfN(gen, { n: 4, rewardFn: ({ prediction }) => prediction.summary.length, }); // Whole-output assertion: retries with correction feedback. gen.addAssert( (output) => output.summary.includes(topic) || 'Summary must mention the topic.' ); // Streaming assertion: fail fast on unsafe partial output. gen.addStreamingAssert( 'summary', (text) => !text.includes('forbidden'), 'Output contains forbidden text' );
Rules:
addAssert(...) checks the complete parsed output after validation/processors and retries with correction feedback on failure.bestOfN(...) scores complete candidates and returns the highest reward or first threshold hit.refine(...) runs rounds and can feed reward-derived advice into instruction components between rounds.addStreamingAssert(...) targets a string/code output field and receives partial text so far.AxStreamingAssertionError, then feed correction feedback into AxGen retries.typescript// 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:
addFieldProcessor runs once after the field is fully generated.addStreamingFieldProcessor runs on each streaming chunk for the target field.typescriptconst result = await gen.forward(llm, { question: '...' }, { functions: tools, functionCallMode: 'auto', stopFunction: 'finalAnswer', });
Rules:
functionCallMode can be 'auto', 'none', or a specific function name to force.stopFunction accepts a string or string] to halt multi-step on specific function calls.maxSteps reached.typescriptconst gen = ax('question:string -> answer:string', { cachingFunction: async (key, value?) => { if (value !== undefined) { await cache.set(key, value); return; } return await cache.get(key); }, });
typescriptconst result = await gen.forward(llm, { question: '...' }, { contextCache: { cacheBreakpoint: 'after-examples' }, });
Rules:
cachingFunction acts as a get/set: called with (key) to read, (key, value) to write.contextCache enables AI provider-level prompt caching for long context.the chat call. This includes promptCacheKey, sessionId, and contextCache in TypeScript and every generated language package; per-call values take precedence.
typescriptconst 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:
sampleCount generates multiple completions in parallel.resultPicker receives all samples and must return the index of the chosen result.typescriptconst result = await gen.forward(llm, { question: '...' }, { thinkingTokenBudget: 'medium', showThoughts: true, }); console.log(result.thought);
Rules:
thinkingTokenBudget accepts 'none', 'minimal', 'low', 'medium','high', or 'highest'. Provider-specific numeric configuration is only for models such as Gemini 2.5 that expose a numeric thinking budget; Gemini 3 uses model-aware thinking levels instead.
showThoughts: true to include the model's reasoning in result.thought.In TypeScript, providers advertising requiresStructuredOutput (such as Typesafe) automatically receive a schema for scalar-only signatures too. Ax renders JSON instructions/examples and parses the resulting object without changing the program's signature. Typesafe accepts required boolean and class outputs; numeric scoring uses the provider-specific native client. Boolean/class value descriptions map to native criteria, while conventional providers receive readable descriptions in prompts and schemas. See the ax-typesafe skill for native questions, thresholds, and hybrid text generation. Providers that disable both native functions and functionEmulation reject tool-bearing programs before prompt rendering.
typescriptconst sig = f() .input('text', f.string()) .output('summary', f.string()) .output('metadata', f.json().optional()) .useStructured() .build();
Rules:
.useStructured() asks providers with native support, including OpenAI, Anthropic, and Gemini, for schema-constrained JSON.structuredOutputMode: 'auto' follows the selected profile/model's ordered structuredOutputModes capability list. Exact caller modelInfo overrides win over profile model rules and defaults.string or code output can use json_object plus an exact-shape prompt, client-side validation, and bounded correction retries. This optimized path is provider-neutral and does not require provider-visible tools.json_object selection sends no synthetic __axOutput; Ax keeps the exact-shape prompt, strict parsing, and correction retry.__axOutput. It accepts legacy inbound __finalResult calls so stored trajectories remain replayable, and rejects user functions that collide with either reserved name.structuredOutputMode: 'native' to require native schema enforcement; Ax reports an error instead of silently weakening that requirement.structuredOutputMode: 'function' to require the function-argument path; Ax reports an error before sending a request when function calling is unavailable.structuredOutputMode: 'json_object' to require JSON object mode for rich or singleton output; Ax reports an error before transport when the selected profile/model has not verified it.json_schema and json_object chat requests validate their corresponding capabilities independently. structuredOutputs remains the compatibility alias for native JSON Schema only.providerMetadata.ax.structured_output_rung (native, function, or json_object).required, set additionalProperties: false on objects, and express optional fields as nullable types.json fields and unshaped object fields are sent as JSON-encoded strings for native structured outputs, then parsed back into normal JavaScript values.typescriptconst 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`); }, }, });
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 statesetModel(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 executionRules:
beforeStep runs before each LLM call; afterStep runs after.afterFunctionExecution to react to specific function results.typescript// 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: true enables automatic model and parameter selection.selfTuning.functions provides a pool of functions the tuner may add or remove per step.typescriptimport { 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:
AxGenerateError includes details with model and signature for debugging.AxAIServiceAbortedError is thrown on cancellation via stop() or abortSignal.After any .forward() or streamingForward() call, gen.getChatLog() returns the full normalized chat history — every ai.chat() round-trip, including the system prompt, all messages, and the model response. The log is reset at the start of each .forward() call. Multi-step generators (with function calls) produce one entry per step.
typescriptawait gen.forward(llm, { question: 'What is 2+2?' }); for (const entry of gen.getChatLog()) { console.log('model:', entry.model); for (const msg of entry.messages) { console.log(`[${msg.role}]`, msg.content); } console.log('tokens:', entry.modelUsage?.tokens); }
Message roles: system, user, assistant, tool. Assistant content uses inline XML:
<think>...</think> — reasoning/thinking tokens<tool_call>\n{...}\n</tool_call> — tool invocationsThe system message includes a <tools> JSON block when functions are present.
typescripttype AxChatLogMessage = | { role: 'system'; content: string } | { role: 'user'; content: string } | { role: 'assistant'; content: string } | { role: 'tool'; name: string; content: string }; type AxChatLogEntry = { name?: string; model: string; messages: AxChatLogMessage[]; modelUsage?: AxProgramUsage; }; gen.getChatLog(): readonly AxChatLogEntry[]
Returns token usage aggregated by (ai, model) across all steps. When a provider reports prompt-cache usage, promptTokens is the uncached input portion and cacheReadTokens / cacheCreationTokens carry the cache counters. Reset with resetUsage().
typescriptconst usage = gen.getUsage(); // AxProgramUsage[] console.log(usage[0]?.tokens?.promptTokens); gen.resetUsage();
AxAgent and AxFlow also return flat AxChatLogEntry[] logs; composite programs set entry.name so callers can filter by node/stage.
Fetch these for full working code:
Use ax-mcp for client construction, transports, authentication, catalog and task APIs, subscriptions, event routing, and recording/replay. This section only covers the AxGen attachment boundary.
Pass live clients directly to constructor or forward options:
typescriptconst gen = ax('question:string -> answer:string', { mcp: [docs, search] }); const result = await gen.forward(llm, { question }, { mcpContext: [ { client: 'docs', resource: { uri: 'docs://guide' } }, ], });
The model receives native tool definitions. Structured, image, audio, resource-link, embedded-resource, metadata, task, and error results are preserved until the provider adapter maps supported content. Streaming keeps MCP progress/task events separate from Ax output. Never call toFunction() for native integration.
Use client.inspectCatalog() when an endpoint is the only configuration. It discovers server-owned tool/prompt names, concrete resource URIs, and URI templates. Event sources require an explicit none/all/URI/selector resource subscription policy and never create a wake route implicitly.
Under an event target, a required task-backed MCP tool registers the owning namespace:taskId continuation automatically. Use AxMCPEventSource plus axMCPEventRoutes to observe progress and resume the target on input_required or a terminal state.
Wrap an AxGen with eventTarget('id').program(gen).ai(ai).input(...).build() to invoke it from an explicit wake or resume route. Use segment-safe eventPath selectors; projection and explicit fields are validated against the AxGen signature before invocation. Use .wakeInput() and .resumeInput() for different action contracts. Streaming targets persist each chunk before optional chunk sinks and persist the final result before final sinks.
Use a reusable eventInput().project(...).field(...) plan when mapping should be callback-free. Callback mapInput remains available, but its result is cloned, stripped to declared AxGen inputs, and signature-validated before the first model call; mapper exceptions become non-retryable event_input_invalid deliveries.
new AxGen(...) for new code unless explicitly required.ai(...) instance is expected.forward() for streaming; use streamingForward().maxSteps is reached.Declare independent host tools with .execution('background'). AxGen automatically uses supported async sessions, submits results, and validates the final answer after pending work. Use asyncMode: 'off' for the ordinary loop. Attach runControl() through { control } for steering, reasoning updates, and cancellation. Streamed session output is provisional until the run completes. Reset accumulated output when its version changes; the final output still passes assertions and field validation. Streaming assertions run before provisional text is emitted. An assertion may trigger a correction before tools start; after host work starts, a mid-stream assertion fails the run without replaying that work.
For automatic tool runs and controller-attached runs, routers and balancers resolve a provider before execution and pin it for the run. Mixed balancers use sessions only when the selected provider supports them. Providers implementing only .chat() continue through the ordinary loop.
Generated-language status: C++ session tools with raw JSON schemas validate required properties and argument types before their handlers start. Invalid arguments enter the correction loop; exhausting the step limit fails the run. This does not establish support for every JSON Schema constraint. Generated session parity remains open; see docs/COMPILER.md.
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→pass | 20,386 | 12,741 | -38% | 1 | 1 | 0% | 3,050 | 7,612 | +150% | 0 | 0 | — |
case-02 | fail→pass | 18,897 | 12,172 | -36% | 1 | 1 | 0% | 2,626 | 7,581 | +189% | 0 | 0 | — |
case-03 | fail→pass | 25,774 | 13,578 | -47% | 1 | 1 | 0% | 4,131 | 7,827 | +89% | 0 | 0 | — |
case-04 | fail→pass | 13,872 | 9,382 | -32% | 1 | 1 | 0% | 1,623 | 6,805 | +319% | 0 | 0 | — |
case-05 | fail→pass | 17,086 | 8,454 | -51% | 1 | 1 | 0% | 2,467 | 6,573 | +166% | 0 | 0 | — |
case-06 | fail→pass | 18,649 | 9,829 | -47% | 1 | 1 | 0% | 2,604 | 6,939 | +166% | 0 | 0 | — |
case-07 | fail→pass | 19,294 | 10,654 | -45% | 1 | 1 | 0% | 2,806 | 7,099 | +153% | 0 | 0 | — |
case-08 | fail→pass | 19,805 | 10,966 | -45% | 1 | 1 | 0% | 2,785 | 7,165 | +157% | 0 | 0 | — |
case-09 | fail→pass | 32,063 | 10,888 | -66% | 1 | 1 | 0% | 5,259 | 7,134 | +36% | 0 | 0 | — |
case-10 | fail→pass | 19,109 | 9,445 | -51% | 1 | 1 | 0% | 2,593 | 6,803 | +162% | 0 | 0 | — |
case-11 | fail→pass | 26,505 | 5,409 | -80% | 1 | 1 | 0% | 4,319 | 7,076 | +64% | 0 | 0 | — |
case-12 | fail→pass | 23,526 | 11,183 | -52% | 1 | 1 | 0% | 3,295 | 6,967 | +111% | 0 | 0 | — |
case-13 | fail→pass | 20,308 | 10,487 | -48% | 1 | 1 | 0% | 3,141 | 7,005 | +123% | 0 | 0 | — |
case-14 | fail→pass | 26,966 | 11,205 | -58% | 1 | 1 | 0% | 4,641 | 7,244 | +56% | 0 | 0 | — |
case-15 | fail→pass | 20,921 | 9,456 | -55% | 1 | 1 | 0% | 3,337 | 6,854 | +105% | 0 | 0 | — |
case-16 | fail→pass | 27,662 | 10,377 | -62% | 1 | 1 | 0% | 4,671 | 7,028 | +50% | 0 | 0 | — |
case-17 | fail→pass | 44,306 | 8,676 | -80% | 1 | 1 | 0% | 1,833 | 6,629 | +262% | 0 | 0 | — |
case-23 | pass→pass | 17,561 | 15,079 | -14% | 1 | 1 | 0% | 2,827 | 8,285 | +193% | 0 | 0 | — |
case-18 | fail→pass | 18,416 | 11,035 | -40% | 1 | 1 | 0% | 2,225 | 7,139 | +221% | 0 | 0 | — |
case-19 | fail→pass | 23,221 | 12,145 | -48% | 1 | 1 | 0% | 3,657 | 7,262 | +99% | 0 | 0 | — |
case-20 | fail→pass | 27,000 | 12,960 | -52% | 1 | 1 | 0% | 3,815 | 7,519 | +97% | 0 | 0 | — |
case-21 | pass→pass | 17,738 | 9,473 | -47% | 1 | 1 | 0% | 2,337 | 6,794 | +191% | 0 | 0 | — |
case-22 | fail→pass | 24,001 | 12,657 | -47% | 1 | 1 | 0% | 3,348 | 7,728 | +131% | 0 | 0 | — |
case-24 | pass→pass | 20,868 | 12,113 | -42% | 1 | 1 | 0% | 3,657 | 7,373 | +102% | 0 | 0 | — |
case-25 | pass→pass | 10,245 | 10,163 | -1% | 1 | 1 | 0% | 1,007 | 6,998 | +595% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 25 cases were attempted, and 24 counted toward the lift figure. The other 1 produced results that are not comparable between the two arms, so they are excluded from the headline rather than averaged into it. The headline lift of +84 percentage points is the difference between those two pass rates over the 24 comparable cases.
The publisher has shipped newer versions since this run, so these numbers describe v6, not the version currently listed.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
| Model | Method | Date | Lift |
|---|---|---|---|
| gemini-3.6-flash | verified | 9/2/2026 | +86% |
| gemini-3.6-flash | verified | 8/26/2026 | +77% |
| gemini-3.6-flash | verified | 8/17/2026 | +68% |
| gemini-3.6-flash | verified | 8/11/2026 | +84% |
Other measured skills in the registry, with their headline benchmark lift.