Skip to content
10 min read · 1,981 words

Interface: TransformersJsAdapterOptions ​

Defined in: src/batteries/llm/transformers_js/types.ts:172

Configuration for the transformers.js LLM adapter.

Remarks ​

Three groups: engine (model + loading), generation (transformers.js generate kwargs), and ADK-control (shared with the other LLM batteries), the last including the two text-parser selectors that make this battery work: transformers.js does NOT return structured tool calls or reasoning — the model emits them as family-specific text, and toolCallParser / reasoningParser choose how that text is parsed.

Extends ​

Properties ​

PropertyTypeDescriptionInherited fromDefined in
autoAck?booleanAutomatically ctx.ack() when generation completes with no tool calls (default false).-src/batteries/llm/transformers_js/types.ts:298
bucketOrder?ChatCompletionsBucketOrderOrder in which the leading/trailing context buckets are rendered.-src/batteries/llm/transformers_js/types.ts:278
contextWindow?numberHard context-window token budget; enforced only when tokenEncoding is non-null.-src/batteries/llm/transformers_js/types.ts:280
createMultimodal?CreateTransformersJsMultimodalCustom multimodal model+processor factory; overrides the default Auto* loaders.-src/batteries/llm/transformers_js/types.ts:226
createPipeline?CreateTransformersJsPipelineCustom pipeline factory; overrides the default pipeline('text-generation', …) loader.-src/batteries/llm/transformers_js/types.ts:179
createStreamer?CreateTransformersJsStreamerCustom streaming-sink factory; overrides the default TextStreamer (avoids importing the peer).-src/batteries/llm/transformers_js/types.ts:181
device?TransformersJsDeviceInference device. A single value, or — for a multimodal model — a Record keyed by submodule filename (vision_encoder/audio_encoder/embed_tokens/decoder_model_merged) to configure each separately. Default: transformers.js environment default.-src/batteries/llm/transformers_js/types.ts:187
doSample?booleanNative sample flag (do_sample); false = greedy. Prefer sampler.-src/batteries/llm/transformers_js/types.ts:254
dtype?TransformersJsDtypeQuantization/precision dtype (e.g. 'q4f16'), or a per-submodule Record (see device).-src/batteries/llm/transformers_js/types.ts:189
enableThinking?booleanWhether to enable the model's "thinking"/reasoning mode, passed EXPLICITLY to the chat template as enable_thinking. Defaults to false — many reasoning templates (Qwen3, DeepSeek-R1) default thinking ON, which silently burns the token budget inside <think> and leaves empty prose. We pin it off unless you opt in. (Independent of reasoningParser, which only parses thinking that IS emitted.) Part of the shared ChatGenerationOptions contract.-src/batteries/llm/transformers_js/types.ts:272
extractMediaOutputs?MediaOutputExtractorFnExtract GENERATED media (audio/image/…) from the raw generation result and surface it as attachments on the assistant @nhtio/adk!Message. Default absent → text-only output, byte-for-byte unchanged. The tested open-weight chat checkpoints emit only text; supply this when wrapping a media-emitting model. Receives the raw transformers.js generation object (the model.generate / pipeline output); each returned MediaOutputExtractorFn descriptor is persisted via ctx.storeMediaBytes and attached as a Media.toolGenerated(...).-src/batteries/llm/transformers_js/types.ts:334
forgeToolsFilter?(forged: ToolRegistry, ctx: DispatchContext) => ToolRegistryOPTIONAL hook to SHAPE the artifact-query tools forged from prior-turn SpooledArtifact results, before they merge into the visible tool set. Receives the merged forged registry + dispatch context; returns a (possibly narrowed) registry, applied BEFORE the merge with ctx.tools. Lets the assembler keep only the core readers on a tight window (the rest reachable via tool_catalog/call_a_tool). Default absent = identity = backward-compatible. The battery stays budget-agnostic (per the CONTRIBUTING size-threshold rule) — it applies the supplied filter without measuring context; budget logic lives in the caller.-src/batteries/llm/transformers_js/types.ts:313
helpers?Partial<ChatCompletionsHelpers>Pluggable per-function overrides for the rendering/translation helpers.-src/batteries/llm/transformers_js/types.ts:292
isAvailable?() => booleanOverride the availability probe. Default: true whenever the peer is importable (env-neutral).-src/batteries/llm/transformers_js/types.ts:233
maxNewTokens?numberNative max tokens (max_new_tokens). Prefer maxTokens. Default 1024.-src/batteries/llm/transformers_js/types.ts:252
maxTokens?numberPortable max generation length (canonical spelling of maxNewTokens). Default 1024.-src/batteries/llm/transformers_js/types.ts:240
modelstringThe model id (e.g. onnx-community/gemma-4-E2B-it-ONNX). Required; no default.-src/batteries/llm/transformers_js/types.ts:175
modelSource?TransformersJsModelSourceCustom model-source resolver (OPFS / separate-source / per-submodule loading). Wraps transformers.js's env.customCache; serves each model file from any source. Dual-environment (Node + browser).-src/batteries/llm/transformers_js/types.ts:231
multimodal?| boolean | { audio?: boolean; image?: boolean; }Enable multimodal (image/audio) input. Default off → the text-only path is byte-for-byte unchanged. When on, the model loads via AutoModelForImageTextToText + AutoProcessor (not the text-generation pipeline), and Media attachments on a Message are fed to the model. true = both modalities the model supports; {image?,audio?} restricts which Media kinds are sent natively (others degrade via unsupportedMediaPolicy). Output is still text → the tool-call/reasoning parsers are unaffected.-src/batteries/llm/transformers_js/types.ts:222
multimodalEngine?{ model: PreTrainedModel; processor: Processor; }A pre-built multimodal model+processor pair; mutually exclusive with createMultimodal.-src/batteries/llm/transformers_js/types.ts:224
multimodalEngine.modelPreTrainedModel--src/batteries/llm/transformers_js/types.ts:224
multimodalEngine.processorProcessor--src/batteries/llm/transformers_js/types.ts:224
onCompiling?BatteryLifecycleCallbackEngine/graph/shader compilation after download, before the first token. A COARSE marker: the on-device runtimes (LiteRT Engine.create, transformers.js from_pretrained) expose the boundary — download done, opaque WebGPU/WASM graph build about to run — but NOT a progress stream, so progress is usually absent. Often the slowest part of a cold start; without this it was invisible.BatteryLifecycleHooks.onCompilingsrc/batteries/llm/chat_common/lifecycle.ts:95
onComplete?BatteryLifecycleCallbackAfter the turn's output is parsed + persisted, before ack (fires per turn).BatteryLifecycleHooks.onCompletesrc/batteries/llm/chat_common/lifecycle.ts:105
onError?BatteryLifecycleCallbackA load or generation failure (paired with nack).BatteryLifecycleHooks.onErrorsrc/batteries/llm/chat_common/lifecycle.ts:107
onGenerating?BatteryLifecycleCallbackThe generate call is in progress (fires per turn). Fires once immediately before the provider call for most engines; engines that stream per-step generation progress (e.g. a diffusion denoise loop) fire it REPEATEDLY during generation, each carrying a progress in 0..1.BatteryLifecycleHooks.onGeneratingsrc/batteries/llm/chat_common/lifecycle.ts:103
onInitProgress?ProgressCallbackCalled with model-load progress reports while weights download/compile.-src/batteries/llm/transformers_js/types.ts:214
onLifecycle?BatteryLifecycleCallbackFires on EVERY phase transition (the firehose).BatteryLifecycleHooks.onLifecyclesrc/batteries/llm/chat_common/lifecycle.ts:86
onLoading?BatteryLifecycleCallbackWeights/runtime loading — may fire repeatedly with progress as the provider reports it.BatteryLifecycleHooks.onLoadingsrc/batteries/llm/chat_common/lifecycle.ts:88
onPromptAssembled?PromptAssembledObserverFnObserve the fully-assembled prompt this battery is about to send TO the model — fired once per terminal generation, the instant assembly completes and BEFORE the pipeline/generate dispatch, with the per-turn messages and the tools handed to apply_chat_template. The mirror of onRawGeneration. Purely observational (return value ignored, errors swallowed). Default absent. The request is handed back AS-IS — no redaction — so treat it as potentially sensitive if you persist it. See PromptAssembledObserverFn.-src/batteries/llm/transformers_js/types.ts:353
onRawGeneration?RawGenerationObserverFnObserve the model's RAW text output for each completed generation — fired once per terminal generation, after envelope-stripping + reasoning/tool-call parsing but before the result is persisted, with the complete rawText, the residual cleanedText, and the extracted reasoning / toolCalls. Purely observational (return value ignored, errors swallowed). Default absent. This is the supported seam for parser bring-up against a new model, live "why did it abstain?" debugging, and ground-truth fixture capture — the job that previously needed a temporary hook patched into the adapter. See RawGenerationObserverFn.-src/batteries/llm/transformers_js/types.ts:344
onReady?BatteryLifecycleCallbackEngine/pipeline resolved and cached, before the first generation.BatteryLifecycleHooks.onReadysrc/batteries/llm/chat_common/lifecycle.ts:97
pinKvCacheToGpu?booleanPin the autoregressive KV cache (present.* outputs) to GPU buffers on the WebGPU EP, keeping it OFF the ONNX-Runtime-Web wasm32 linear-memory heap (hard-capped at 4 GiB). Default true. Remarks This is the battery's headline in-browser memory default: the wasm32 heap is the wall hit first when running on the WASM/JSEP WebGPU path, and the KV cache is its largest growing consumer across a multi-generate turn. transformers.js is supposed to pin this automatically, but its auto-pin silently no-ops on models with nested config (e.g. Gemma-4's text_config) — leaving the KV cache on the wasm heap. We apply the pin explicitly by default so the common case "just works". The ESCAPE HATCH: set false to disable entirely, or set your own sessionOptions.preferredOutputLocation — an explicit value ALWAYS wins and is never overwritten. No effect off the WebGPU EP (there is no 'gpu-buffer' location on the wasm/cpu backend).-src/batteries/llm/transformers_js/types.ts:212
pipeline?TextGenerationPipelineA pre-built text-generation pipeline to drive; mutually exclusive with createPipeline.-src/batteries/llm/transformers_js/types.ts:177
reasoningFieldPrecedence?ReasoningFieldPrecedencePrecedence order for reasoning/thought fields.-src/batteries/llm/transformers_js/types.ts:290
reasoningOrphanRecovery?booleanRecover UNPAIRED reasoning markers (a lone </think>, a truncated <think>) by inferring the missing half from the pseudo-streaming order, instead of leaking the stray marker into the visible answer. Defaults to true. Set false for strict pair-only parsing. Ignored when reasoningParser is a custom function. Motivated by real gemma-4-E4B WebGPU "randomly emits </think>" drift.-src/batteries/llm/transformers_js/types.ts:325
reasoningParser?| ReasoningParserName | ReasoningParserFnHow to parse reasoning/thinking out of the model's text output. A family name, 'auto' (the default), 'none', or a custom ReasoningParserFn. Extracted reasoning becomes ADK Thoughts.-src/batteries/llm/transformers_js/types.ts:318
repetitionPenalty?numberRepetition penalty (always sent). Default 1.1.-src/batteries/llm/transformers_js/types.ts:262
replayCompatibility?readonly string[]Replay-compatibility tags whose opaque reasoning payloads may be replayed.-src/batteries/llm/transformers_js/types.ts:288
sampler?ChatSamplerPortable sampler strategy ('greedy' default). 'greedy'→do_sample:false; 'top-k'/'top-p'→ do_sample:true+the matching cutoff. Canonical spelling of doSample.-src/batteries/llm/transformers_js/types.ts:243
seed?numberRNG seed for reproducible sampling (best-effort).-src/batteries/llm/transformers_js/types.ts:245
selfIdentity?stringThe assistant identity this adapter speaks as (default 'assistant').-src/batteries/llm/transformers_js/types.ts:282
sessionOptions?TransformersJsSessionOptionsONNX Runtime session options forwarded verbatim to the loader's session_options arg (both the pipeline and multimodal paths). A REACHABLE LEVER for advanced WebGPU memory/perf control — surfaced, never auto-applied. See TransformersJsSessionOptions for useful keys. The battery sets no default here; whatever you pass is what the runtime gets.-src/batteries/llm/transformers_js/types.ts:196
spoolStore?SpoolStoreByte store for spooling raw tool output (defaults to a per-dispatch in-memory store).-src/batteries/llm/transformers_js/types.ts:294
stopStrings?readonly string[]Stop strings that halt generation.-src/batteries/llm/transformers_js/types.ts:264
stream?booleanStream tokens (default true). When false, a single completed message is returned.-src/batteries/llm/transformers_js/types.ts:276
temperature?numberSampling temperature. Default 0.7.-src/batteries/llm/transformers_js/types.ts:256
thoughtSurfacing?"all" | "all-self" | "latest-self"Which thoughts are surfaced into history.-src/batteries/llm/transformers_js/types.ts:284
tokenEncoding?| TokenEncodingId | nullToken encoding used for context-window accounting, or null to disable (default null).-src/batteries/llm/transformers_js/types.ts:286
toolCallParser?| ToolCallParserName | ToolCallParserFnHow to parse tool calls out of the model's text output (transformers.js does not return them structured). A family name, 'auto' (try-all in priority order — the default), 'none' (disable), or a custom ToolCallParserFn.-src/batteries/llm/transformers_js/types.ts:304
topK?numberTop-K cutoff. Default 40.-src/batteries/llm/transformers_js/types.ts:258
topP?numberTop-P (nucleus) cutoff. Default 0.95.-src/batteries/llm/transformers_js/types.ts:260
unsupportedMediaPolicy?UnsupportedMediaPolicyHow to handle media the model cannot natively consume (default 'throw').-src/batteries/llm/transformers_js/types.ts:296