Casai documentation
Open interactive documentation · Download the complete Markdown source
All chapters and component contracts, with shared rules and representative examples. Readable without JavaScript and rendered directly from the same Markdown download.
Interactive documentation - Read all HTML
Versions: casai 0.6.2, ai 7.0.162, @ai-sdk/provider-utils 5.0.74, @ai-sdk/provider 4.0.35, cascada-engine 0.7.0
Source revision: 2053fe80ee8f45513a6254b0d37ed0ab7bf7c3c2 (includes local changes). Exact snapshot and file hashes.
- Introduction
- Build your first workflow.
- Create and call components
- Orchestrate concurrent workflows
- Prepare inputs and validate results
- Share configuration
- Use tools and delegate tasks
- Stream and combine results
- Work with images, audio and video
- Manage conversations
- Connect application interfaces
- Load and organize sources
- Handle failures and control execution
- Type-check and test workflows
- Examples and further reading
- Component reference
- Source modifiers
- Shared properties
- Calls and methods
- Types and result fields
Introduction
Casai combines AI agents, templates, scripts and JavaScript/TypeScript code into reusable workflows. Write the workflow logic in CascadaScript - a simple, instantly familiar language with automatic concurrency - to call components, make decisions and combine results.
- Concurrency and streaming: Independent operations run concurrently without extra code, and streaming lets you use results as they arrive.
- Components - create, reuse and swap: Reusable components have a common calling interface and compose directly from Cascada. Components are stateless; returned state can be passed between calls.
- The context object - structured data input: Turn your own structured data into component input with a template, script or function.
- Shared configuration - inherit and specialize: Components inherit models, tools and defaults from a
Configor another component, overriding only what changes. - Call tools: Agents, templates, scripts and functions can call AI SDK tools, including MCP tools.
- Turn a component into a tool: Add
.asTooland aninputSchemato turn almost any component into a tool that agents and workflows can call.
Concurrent AI orchestration for JavaScript and TypeScript. The component reference provides the complete API alongside these chapters.
Build your first workflow.
Use Node.js 24 or later, AI SDK 7.x (7.0.162+) and Zod 4.x (4.6.5+). Install the latest releases within these supported major versions:
npm install casai ai@7 zod@4
Then install the provider you want to use. Choose one, or add more as needed:
| Provider | Install | API key environment variable |
|---|---|---|
| OpenAI | npm install @ai-sdk/openai@4 |
OPENAI_API_KEY |
| Anthropic | npm install @ai-sdk/anthropic@4 |
ANTHROPIC_API_KEY |
npm install @ai-sdk/google@4 |
GOOGLE_GENERATIVE_AI_API_KEY |
Each command selects the latest 4.x release of that provider package. The workflow below uses OpenAI; see the AI SDK provider directory for more options.
Use TypeScript 7.0.2 or newer with strictNullChecks enabled (normally through strict: true). This workflow runs on a Node.js server, where you keep provider credentials and private tools. Browser chat clients call that server. For a browser voice conversation, use the AI SDK’s realtime client with Casai’s VoiceAgentBackend. Audio with and without node-av · Browser voice sessions
Use ESM imports in your JavaScript or TypeScript application ("type": "module" in package.json). Run provider calls in your server or Node.js process, with credentials in its environment. For a local example, create .env:
OPENAI_API_KEY=your-api-key
Save the workflow below as quick-start.ts, then run it with Node's environment-file support:
node --env-file=.env quick-start.ts
Casai does not load .env itself. Specialized components require the corresponding provider model type, rather than reusing a language-model instance; check your provider's supported capabilities.
import { create, z } from 'casai';
import { openai } from '@ai-sdk/openai';
const model = openai('gpt-4o-mini');
const explain = create.LLMAgent.withTemplate({
model,
inputSchema: z.object({ topic: z.string() }),
prompt: 'Explain {{ topic }} in two sentences.',
});
const suggest = create.LLMAgent.withTemplate({
model,
inputSchema: z.object({ topic: z.string() }),
prompt: 'Suggest one practical exercise for learning {{ topic }}.',
});
const workflow = create.Script({
context: { explain, suggest },
inputSchema: z.object({ topic: z.string() }),
script: `
var explanation = explain({ topic: topic }).output
var exercise = suggest({ topic: topic }).output
return { explanation: explanation, exercise: exercise }
`,
});
console.log(await workflow({ topic: 'solar energy' }));
The two agents run concurrently because neither needs the other's result. The return waits for both and gives you an object with explanation and exercise strings. The wording varies with the model. This is ordinary sequential CascadaScript: the runtime follows logical dependencies and starts independent work as soon as possible, while preserving source-order results. No manual promise coordination or graph wiring is needed.
The examples throughout this documentation assume the indicated application dependencies. Names such as embeddingModel and speechModel mean models for those operations, supplied by your provider. Examples marked Work in progress describe planned capabilities; the component reference carries their status too.
Create and call components
Create a component once, then call it with different inputs. It holds reusable configuration, not the current conversation, invocation or session. Returned state belongs to the caller. Use the component reference to choose an operation and inspect its precise inputs and results.
Creating and Calling Components
Pass reusable settings to a factory, then supply task-specific input to the component it returns:
const writer = create.LLMAgent({ model, prompt: 'Write a short welcome message.' });
const welcome = await writer();
console.log(welcome.output);
const invitation = await writer('Write a short invitation to a community dinner.');
Each component has a main property, the input its operation works on, such as an LLMAgent's prompt or a Template's template. You set it when creating the component, and a call can replace it for one invocation. The component's input modifier sets its type, never its name: on a plain LLMAgent, prompt is literal text or model messages; with .withTemplate, it is a template; with .loadsTemplate, a template's name. Replacements follow the selected source mode. ImageGenerator also supports replacing text while retaining configured reference images and mask.
The ordinary call, component(...), takes the main input first, including object or array inputs, followed by the operation's common parameters. A plain LLMAgent takes (prompt, context?, messageHistory?), with context omitted before history when no call data is required; positional prompt overrides are strings, while message arrays always supply history. New message arrays use the named prompt field. Prepared/loaded forms take source, context, and secondary parameters in that order, omitting source to use the configured one. Image media follow context, just like reranker documents. Every callable component has .run({ ... }) for the same named inputs and additional execution settings. Native SDK abort/timeout controls and explicit cooperative signals on coded-component .run() remain available. See cancellation and timeouts.
See each component's call signature and supported inputs in the reference.
A Function's callback can't be replaced per call, so a Function is called with its context alone. VoiceAgentBackend's main property is its session instructions; an LLMAgent's instructions setting is separate and never rendered.
Inputs are optional when configuration guarantees them or the SDK allows omission. When the next argument identifies its role, omit the unused slot: reranker(query, 5) uses configured documents; edit(template, context, images) omits mask; draw(text, 3) requests a count without media. Required unresolved inputs still need values. A first string remains source, so speaker(undefined, 'alloy') changes only the voice when text is configured. A lone ordinary object on a rendered component remains context. Use undefined placeholders for cases sharing the same type. Model selection, lifecycle controls and less common parameters use configuration or .run().
Prepared forms preserve source, context and secondary-input order, with image media following preparation context. Examples include reranker(context, documents, topN), speaker(context, voice) and transcriberStream(context, inputAudioFormat). With source override and omittable context, speaker(template, voice) needs no context placeholder. Image forms include edit(template, context, images, n) with omitted mask; edit(template, images) can omit satisfied context. Function preparers are distinguishable source overrides; a standalone Function's implementation stays fixed. A rendered Reranker can omit context before documents/topN when its context contract permits omission.
Calls return promises; the shared returned-value reference explains direct values, streams and SDK result objects.
A Template, for example, accepts a one-off template before its context:
const greeting = create.Template({
template: 'Hello {{ name }}!',
context: { name: 'World' },
inputSchema: z.object({ name: z.string() }),
});
console.log(await greeting()); // Hello World!
console.log(await greeting({ name: 'Ada' })); // Hello Ada!
console.log(await greeting('Welcome {{ name }}.', { name: 'Ada' }));
An object supplied as rendering context is data. For example, a field named prompt inside that object is a template variable; it does not override the component's prompt setting. There is no input wrapper around ordinary calls. Put user data in the context, never in a rendered component's main property, where it would run as template or script code.
If a model-derived value might be either an object or a string, put it in an explicitly declared data field: component({ payload: modelValue }) or .run({ context: { payload: modelValue } }), with an input schema accepting that field's data. Passing component(modelValue) to a rendered component would interpret a string as source. Context values are not evaluated again as source, even when they contain template syntax or fields named prompt, template, or script.
To inherit shared settings, pass a Config or a compatible component as the factory's second argument. See configuration management for how settings are merged.
Factories are also named exports: import { LLMAgent, Template, Script } from 'casai' lets you write LLMAgent(...) instead of create.LLMAgent(...).
Returned Values
Ordinary calls and .run() return promises. After await, Template, Script and Function give you the application value itself. LLMAgent gives you an SDK result containing the application output in .output.
| Component | Output configuration | What await component(...) returns |
|---|---|---|
| Template | Implicit text; no output schema | A rendered string, or a text stream with .asStream |
| Script / Function | Optional schema |
The schema's parsed output; without a schema, the program/callback's returned value |
| LLMAgent | SDK output, defaulting to text |
The full SDK result, with .output, history and native SDK fields; see LLMAgent results |
| Other model components | The operation's native output contract | Its native result, such as embeddings, images or transcription data; see the component overview |
The actual output-setting names are schema for Script/Function and output for LLMAgent; there is no shared outputSchema property. A schema's returned value is used, including defaults, stripping and transforms. Script/Function producers return schema input; their callers receive schema output directly, without an added .output envelope.
A stream schema parses each element as the caller consumes it. On a streaming LLMAgent, read textStream for live text and await output for the completed application value. Stream schemas · LLMAgent results
To interchange model and coded implementations in a workflow, have a small adapter extract the model result's application value. The workflow can then consume the same value type from either implementation; see replacement examples.
Named Arguments and Per-Call Overrides
The shorthand caller is the primary API and retains its input forms. Every callable component also has .run({ ... }) for named inputs and permitted per-call settings, returning the same result in the same mode as the ordinary call. Calls and .run() return promises and reject on invocation errors; invalid configuration throws when the component is created. For streaming, awaiting the call obtains the live handle without waiting for completion.
Anything required that the shorthand cannot supply must be satisfied by resolved configuration, including inherited values. For example, registered tools with required trusted context need configured toolsContext entries. .run() can override that context for one call; it does not make an incomplete finished component usable. Reusable Config fragments may remain incomplete. Their runtime checks cover common configuration structure; the completed component validates its supported settings. TypeScript also checks known fragment incompatibilities during authoring.
Transcriber accepts (audio, inputAudioFormat) for raw audio in either delivery mode; without inputAudioFormat, an ordinary call uses encoded-file transcription. Both Translator modes accept (audio, inputAudioFormat, targetLanguage). Configured values permit the existing unambiguous omissions; if only a raw format is missing, (undefined, inputAudioFormat) retains configured audio. In .loadsAudio, audio becomes the file/URL resource and inputAudioFormat remains the model target. Source demuxer and track selection belong in mediaSettings, with no positional slots.
Template accepts .run({ template, context, toolsContext, abortSignal, timeout }), Script accepts .run({ script, context, toolsContext, abortSignal, timeout }), and Function accepts .run({ context, toolsContext, abortSignal, timeout }). Omit a source to use its configured value. toolsContext supplies invocation-specific data to registered tools; it merges by tool name, replacing each supplied entry as a whole. Function's execute callback and schemas remain fixed. Signals are forwarded to cooperative operations. A timeout can stop waiting without forcibly interrupting arbitrary JavaScript or rendering; see cancellation and timeouts.
const detailed = await explain.run({
prompt: 'Explain {{ topic }} with one practical example for {{ audience }}.',
context: { topic: 'solar panels', audience: 'a homeowner' },
maxOutputTokens: 600,
});
explain is a .withTemplate agent, so the call-time prompt is a template, like the configured one.
The .run() object is an application-authored settings envelope. Put application/model data inside context; do not pass or spread that data as the settings object. Template, Script, and Function reject unknown top-level keys with ValidationError, while SDK settings retain SDK validation. This catches many mistaken calls, but recognized names still select their documented behavior: .run({ template: text }) on Template executes text as source. It is not a safe way to forward model output. The restrictions on settings do not restrict unrelated keys inside context; its input schema and private-binding boundary apply there.
| LLMAgent field | Meaning |
|---|---|
prompt |
The new turn, replacing the configured prompt. On a plain agent, literal text or model messages; on a rendered agent, a template, script, function, or resource name |
context |
Application input shared by prompt preparation and request/step hooks, including with literal prompts |
messageHistory |
The conversation so far, placed before the new turn |
| Other settings | Model settings, tools, callbacks, stopWhen, cancellation, and other supported per-call settings |
Configured instructions apply to every call. The SDK methods .generate() and .stream() take the SDK's own arguments instead, with a literal conversation.
At the top-level invocation/settings layer, undefined counts as not supplied and leaves the configured value in place. Inside a supplied context object, an own property set to undefined remains an explicit shallow override, just like any other value. With configured name: 'Ada' and a schema field z.string().default('x'), passing { name: undefined } therefore produces 'x'; omitting name retains 'Ada'. This preserves the existing merge rules. LLMAgent lifecycle observers compose with configured observers; control hooks such as prepareCall, prepareStep, and onError replace the configured callback. See callback policies.
Overrides are isolated: concurrent calls can use different inputs, settings, and history without Casai changing shared components or data. Native parsers such as Zod copy declared containers; opaque references and unchanged branches may remain shared. Casai adds no generic copy planner or deep clone of models, helpers, clients, promises, or streams. Schema callbacks must be pure. Component implementations may deliberately mutate authorized state held in context objects or closures; sequence effectful Cascada calls with ! and coordinate shared state across independent runs in the host. Configuration settings stay fixed by contract. See state and snapshot behavior; no freeze or proxy is added.
Output contracts, schemas, the Function execute implementation, renderer setup, and LLMAgent id stay fixed. Derive another component to change them. Agent id is metadata, not a model-call setting or a .run() override.
Specialized components follow the same pattern. Their ordinary call takes the main property by position: route('My order arrived damaged.'), reranker(question, candidates), illustrator('A watercolor workshop'), transcriber(recordedAudio), or speaker('Your replacement is on its way.'). With an input modifier, it also takes the context the main property is prepared with. .run() takes the documented input fields and native settings by name, such as reranker.run({ query, documents, topN: 3 }). VoiceAgentBackend has a session lifecycle.
Generate text and structured results
An LLMAgent prepares a prompt and returns a complete model result. Its default output is text:
import { create } from 'casai';
import { openai } from '@ai-sdk/openai';
import { Output } from 'ai';
import { z } from 'zod';
const model = openai('gpt-4o-mini');
const explain = create.LLMAgent.withTemplate({
model,
prompt: 'Explain {{ topic }} in three short sentences for {{ audience }}.',
context: { audience: 'a beginner' },
inputSchema: z.object({ topic: z.string(), audience: z.string() }),
});
const result = await explain({ topic: 'solar panels' });
console.log(result.output);
The .withTemplate modifier renders the prompt using the call's input and configured context. inputSchema validates caller data merged over schema-declared configured defaults. The declared audience field defaults to 'a beginner' and can be overridden by callers. Undeclared configured bindings remain available to the template but stay outside that parser and cannot be overridden by callers. .output contains the generated text. The result also includes the SDK's usage, steps, and metadata.
Select an output schema when you need typed data:
const extract = create.LLMAgent.withTemplate({
model,
prompt: 'Extract the main ideas from this explanation: {{ text }}',
inputSchema: z.object({ text: z.string() }),
output: Output.object({
schema: z.object({ ideas: z.array(z.string()) }),
}),
});
const ideas = await extract({ text: result.output });
console.log(ideas.output.ideas);
You can call components from a Cascada script to describe the same workflow:
const explainAndExtract = create.Script({
context: { explain, extract },
inputSchema: z.object({ topic: z.string() }),
script: `
var explanation = explain({ topic: topic }).output
var ideas = extract({ text: explanation }).output.ideas
return { explanation: explanation, ideas: ideas }
`,
});
console.log(await explainAndExtract({ topic: 'solar panels' }));
Cascada waits for the explanation before extracting ideas. No await is needed inside the script. Independent operations can run concurrently.
Subsequent snippets use create, Output, z, and model from this setup. Specialized AI components require a model for their own operation; names such as embeddingModel and speechModel stand for instances supplied by your chosen provider.
LLMAgent
LLMAgent generates a complete language-model result, or streams it when created with .asStream. Use it for writing, extraction, classification, image understanding, or tasks involving tools. Text is the default output. The default limit is twenty model steps; without tool activity, execution normally finishes after one. See steps, hooks and continuation.
const writer = create.LLMAgent({ model });
const answer = await writer('Explain battery recycling briefly.');
console.log(answer.output); // Parsed output; a string by default.
console.log(answer.text); // The SDK text accessor is also available.
Plain calls accept prompt text or model messages; rendered forms accept context. All seven input modifiers are supported. .run() accepts named inputs and per-call settings.
Non-tool LLMAgents implement the SDK Agent interface directly; .asTool forms implement the SDK Tool interface. To replace a model operation with coded logic inside a workflow, adapt the SDK result to the workflow's application value contract.
Structured Output
Set output to describe the value you need:
| Desired result | Configuration |
|---|---|
| Text | Omit output, or use Output.text() |
| Validated object | Output.object({ schema }) |
| Array of validated elements | Output.array({ element: schema }) |
| One allowed string | Output.choice({ options: ['yes', 'no'] }) |
| JSON without a fixed schema | Output.json() |
const researcher = create.LLMAgent.withTemplate({
model,
prompt: 'Summarize {{ topic }} in {{ language }}.',
inputSchema: z.object({ topic: z.string() }),
context: { language: 'English' },
output: Output.object({
schema: z.object({ summary: z.string(), findings: z.array(z.string()) }),
}),
});
const report = await researcher({ topic: 'battery recycling' });
console.log(report.output.summary);
output determines parsing, validation and the inferred type of the final application value. It is fixed when the component is created. Structured output can be combined with tools. LLMAgent results · SDK structured output
Use schema descriptions and the output specification's supported name and description fields to explain the desired data to the model. The selected model must support the requested output and tool capabilities; Casai does not make every model support every schema or media type.
LLMAgent Results
After const result = await agent(prompt), pass result.output to the next workflow step. With .asStream, you can display result.textStream as text arrives and then await result.output for the final parsed value from the same run. Each form’s Return tab lists its fields and types. Generation return · Streaming return
When the next step depends on a tool having finished, also inspect the finish reasons and outstanding tool or approval events. A provider can return schema-valid text while work is pending. For example, Anthropic’s raw pause_turn can appear as a normalized stop, and an OpenAI Chat refusal can appear as empty stop text. Save messageHistory if the workflow needs to continue. Once the required input is available, call agent.resume(history, options) with the original application context, relevant per-call settings and any provider state the next request requires, such as an Anthropic container ID. Approvals and continuation
When an outer agent invokes an LLMAgent.asTool, it receives the inner agent’s completed application value. A pause or an unfinished tool call reaches the outer agent as a tool error. Use a directly called agent when your workflow needs to retain and resume the inner conversation. Tool return and completion rules
Orchestrate concurrent workflows
AI agents spend much of their time waiting for models, tools, APIs and databases. CascadaScript lets you express the logic in normal sequential code. The runtime follows logical dependencies: independent operations run concurrently, and each dependent operation starts as soon as its inputs are ready. Results retain sequential source ordering. Sequence intentional external effects with !; concurrency does not make unsynchronized shared state safe.
Script
Script runs a Cascada workflow and returns its value. Use it to call components and combine data; the runtime follows logical dependencies between operations.
const totals = create.Script({
inputSchema: z.object({ price: z.number(), quantity: z.number() }),
schema: z.object({ subtotal: z.number() }),
script: `
var subtotal = price * quantity
return { subtotal: subtotal }
`,
});
console.log(await totals({ price: 12, quantity: 3 })); // { subtotal: 36 }
The main property is script. Call with context, or with a one-off script followed by context. Use return for strings, numbers, objects, arrays, or other supported workflow results. Output validation follows the shared returned-value rules.
.loadsScript loads a named script through a configured loader. .asTool and .loadsScript.asTool expose the workflow as a tool. Both inline and loaded scripts can call helpers or components from context.
A Script streams by returning a stream or tstream channel. This example declares an element stream with a stream schema:
Work in progress: this example requires the planned Cascada native streaming integration.
const guideTitles = create.Script({
inputSchema: z.object({ topics: z.array(z.string()) }),
schema: streamSchema(z.object({ title: z.string() })),
script: `
stream titles
for topic in topics
titles({ title: 'Guide to ' + topic })
endfor
return titles
`,
});
for await (const item of await guideTitles({ topics: ['Solar', 'Wind'] })) {
console.log(item.title);
}
Returning the channel returns the live stream; titles.snapshot() returns a completed array. Elements are parsed lazily before delivery, forwarding their schema-produced values, and Cascada terminates the native stream at its first error after any valid prefix. collectStream(await guideTitles(...)) collects the array or propagates failure. Text output uses a distinct tstream channel with textStreamSchema() and collects into a string. Assigning titles takes a snapshot of the elements emitted before that assignment in source order. An ordinary output schema validates the resulting array/string; assigning a JavaScript stream retains its reference without collecting it.
A Script can also return a JavaScript async iterable produced by a context helper:
import { collectStream } from 'casai';
const numbers = create.Script({
context: {
makeNumbers: async function* () { yield '1'; yield '2'; },
},
schema: streamSchema(z.string().transform(Number)),
script: 'return makeNumbers()',
});
console.log(await collectStream(await numbers())); // [1, 2]
See Cascada script documentation for language syntax and concurrency, and composition examples below.
Function
Function wraps JavaScript logic with reusable configuration and validation. Use it for application services, transformations, or SDK tools.
const normalize = create.Function({
inputSchema: z.object({ text: z.string() }),
schema: z.string(),
execute: ({ text }) => text.trim().toLowerCase(),
});
console.log(await normalize({ text: ' HELLO ' })); // hello
execute may be synchronous or asynchronous; the shared input and output rules apply. Without inputSchema, ordinary arguments beyond the configured private names are inferred from the callback. Declare intentional public overrides of configured fields in inputSchema.
A Function can inherit from a Config or another Function. If a child changes schemas or context incompatibly, provide an execute callback that matches the final configuration. Use .asTool to let an LLMAgent call the function; see tools for execution context and validation behavior.
Template
Template renders text with Cascada. Use it for prompts, reports, messages, or presentation without necessarily making a model call.
const receipt = create.Template({
template: 'Order {{ orderId }} contains {{ count }} items.',
inputSchema: z.object({ orderId: z.string(), count: z.number() }),
});
const text = await receipt({ orderId: 'A123', count: 3 });
console.log(text);
The main property is template. Call with context, or with a one-off template followed by context. Cascada resolves asynchronous context helpers during rendering; see context in templates and scripts.
For a file or named resource, use .loadsTemplate:
import { FileSystemLoader } from 'casai';
const report = create.Template.loadsTemplate({
loader: new FileSystemLoader('./templates'),
template: 'report.njk',
});
console.log(await report({ title: 'Weekly report' }));
In this form, a one-off template is another resource name. .asTool and .loadsTemplate.asTool expose the rendered string as a tool result. Standalone templates default to no HTML escaping; set renderOptions: { autoescape: true } for HTML output.
Place components in context to call them from Cascada. Use scripts to assemble data and templates to format it.
Script for Data Orchestration
This workflow creates a summary and extracts tags independently:
const summarizeText = create.LLMAgent.withTemplate({
model,
inputSchema: z.object({ text: z.string() }),
prompt: 'Summarize in one paragraph: {{ text }}',
});
const extractTags = create.LLMAgent.withTemplate({
model,
inputSchema: z.object({ text: z.string() }),
prompt: 'Extract short topic tags from: {{ text }}',
output: Output.array({ element: z.string() }),
});
const analyze = create.Script({
inputSchema: z.object({ text: z.string() }),
schema: z.object({ summary: z.string(), tags: z.array(z.string()) }),
context: { summarizeText, extractTags },
script: `
var summary = summarizeText({ text: text }).output
var tags = extractTags({ text: text }).output
return { summary: summary, tags: tags }
`,
});
const analysis = await analyze({ text: 'A document about battery recycling.' });
Both operations can run concurrently because neither depends on the other's result. The returned object waits for both. Use ordinary var values and direct returns when assembling structured data.
Template for Presentation
const report = create.Template({
template: `
Summary: {{ summary }}
Tags:
{% for tag in tags %}
- {{ tag }}
{% endfor %}
`,
});
console.log(await report(analysis));
A template can also invoke an asynchronous component directly, for example {{ summarizeText({ text: text }).output }} when summarizeText is a non-streaming text LLMAgent supplied in its context. Casai doesn't detect LLMAgent results, so a template reads .output explicitly, as a Script does. Use JavaScript helpers in context for application-specific behavior; Cascada resolves their promises like component calls.
A streaming agent exposes an async iterable as textStream. Consume it with a supported template async loop, or select promised output when you need completed text:
{% for chunk in writeText({ text: text }).textStream %}{{ chunk }}{% endfor %}
Omitted output and explicit Output.text() both give a promised string through native output. Use textStream for live chunks. Templates collect a text stream during complete rendering and forward its chunks during streaming.
Concurrency, Ordering, and Recovery
Cascada is a separate language with JavaScript-like expressions and its own control-flow syntax. It does not use JavaScript await or try/catch inside a script. Independent statements and for iterations run concurrently, so source order alone does not sequence external side effects.
Use for item in items of 3 to limit a script loop to three concurrent iterations. Use each item in items ... endeach for sequential iterations, or Cascada's sequence / ! facilities for ordered access to stateful services. This concurrency control is separate from an LLMAgent's step limit and Embedder's batch settings.
A deliberately stateful/effectful implementation is a supported use case, not a requirement for a separate stateful-component API. Its application-owned service/session or implementation-owned state may persist across calls; Casai does not automatically store tool results or carry invocation state into later calls. Keep configuration and input bindings unchanged while operating on that authorized state. ! orders the selected scope; it does not make the operation pure, grant permission to change private input bindings, or provide a global lock. Different wrappers that secretly write the same resource are not automatically recognized as one scope. JavaScript calls and native SDK tool execution do not pass through Cascada's !; those callers retain their own ordering and authorization responsibilities.
Sequential calls may reuse state after prior work has finished. Overlapping independent executions need application-managed ownership or coordination; the newer runtime does not enforce a cross-execution lock. Approval also does not deduplicate effects: replaying valid approved history in another SDK invocation can execute the operation again, even when the SDK signs that history. The application or service owns any required idempotency and cross-request deduplication.
Associate persisted conversation and approval history with the authenticated user/session. SDK approval signatures authenticate JSON-compatible public operation data; rich parsed values have native hashing and serialization limitations. Signatures do not bind an operation to private tool context such as the tenant, or authorize access to a requested resource. toolChoice: 'none' is a provider instruction. activeTools and tool-caller routing restrict fresh model calls but do not revoke registered calls already approved in history. Use the SDK's approval policy or service authorization when an operation must be denied.
Approval is also scoped to the model-loop call. A trusted Script, Template or Function that invokes another tool does not automatically run that child's model approval flow. If the outer operation needs approval, configure it there, and enforce essential resource permissions in the service.
Script failures propagate through dependent values while unrelated work can continue. Bind a result and use is error when you want a fallback:
const resilientSummary = create.Script({
context: { summarizeText },
inputSchema: z.object({ text: z.string() }),
script: `
var summary = summarizeText({ text: text }).output
if summary is error
summary = 'Summary unavailable.'
endif
return summary
`,
});
A bare side-effect call discards its result, including a failure; bind and inspect it when the workflow must detect failure. Use direct return values for ordinary data, and channels when ordered concurrent collection is needed. See the Cascada script reference for recovery and sequencing rules.
Choosing Your Orchestration Strategy
Choose the mechanism that expresses who controls the next operation:
| Mechanism | Best suited to |
|---|---|
| JavaScript / Function | Application logic, service integration, and explicit control flow |
| Script | A workflow you define, with dependencies and structured results |
| Template | Text preparation and presentation, including calls to helpers |
| LLMAgent tools | Operations the model chooses while responding to a task |
| Decision | Routing or evaluation through a configured set of questions |
| VoiceAgentBackend + AI SDK realtime client | Run a browser voice conversation with server-side session setup and private tools |
| VoiceAgentClient (planned) | Create independent browser sessions and observe their state from any UI or browser Cascada script |
These can be combined. A Script can call an LLMAgent that uses tools; an LLMAgent tool can run a Script or another LLMAgent; a Template can format the resulting data. Keep reusable application functions in context and expose them as tools when the model should decide whether to invoke them.
Interchanging Components in Workflows
Keep the application operation's input and returned value stable, then put the selected implementation in a workflow's context. LLMAgent returns an SDK result; Template returns text; Script and Function return native values. A small adapter extracts the value the workflow needs from a model result. The workflow then depends on that value contract rather than a model-specific result envelope.
For a worked example that routes support tickets with rules, a model, or both, read Change the implementation. Keep the workflow..
Text Replacements
A text operation can use a Template, a string-returning Function or Script, or an LLMAgent adapter that extracts .output. Keep the accepted input and returned string consistent. Streaming is a separate contract: all replacements must return the expected stream and preserve its completion and error behavior. See streaming contracts, including the current status of Template and Script streaming.
Output Schemas and Structured Replacements
LLMAgent's SDK output and Script/Function's native schema both return schema-produced application values. Each has one declared output-parsing boundary; Casai does not reparse SDK output. Templates stay text-only. Share inputSchema, helper signatures, and the application result type; SDK events, conversation history and the native Agent call protocol remain LLMAgent concerns. Matching types does not guarantee that two implementations make the same decisions.
Draft, review and revise
Use a Script loop when a workflow should revise a result based on structured feedback. Keep a quality target and an iteration limit explicit, and return the final score so the caller can see when the limit was reached. Draft, review, revise - with a stopping point walks through the complete workflow and its stopping rules.
Prepare inputs and validate results
Keep authored code separate from the data it processes. Choose a template, script or function to prepare the component's main input, and declare public data with inputSchema. The source modes and inputSchema reference describe the exact contracts.
Shared Configuration
Pass a flat settings object to a factory. The resulting component exposes its resolved reusable settings as .config; a Config or compatible parent component can supply inherited settings. Supported .run() overrides apply to one invocation.
| Configuration part | Purpose |
|---|---|
context |
Application defaults and private dependencies, such as helpers or clients. Call data combines with these to form one prepared context for the body, prompt preparer and hooks |
inputSchema |
The application input contract. Select declared public defaults, merge call data, then parse before execution; private dependencies stay outside this schema |
| Source / implementation | The component's main property: template, script, Function execute, or LLMAgent prompt with its selected modifier. Other operations use their own input property |
| Output contract | Describes the produced application value, using schema, SDK output, or an implicit/native contract as shown below |
| Operation settings | Model, tool, rendering and execution controls supported by that component |
inputSchema is optional for ordinary components. Its declared fields identify public input and which configured values callers may override. Merge those defaults with call input, parse once, then assemble parsed application values with private bindings. Calls/configuration use schema input types; implementations receive parsed types. Configured defaults can satisfy required fields. With no input schema, configured names remain private, while ordinary calls can supply other application fields. See input and output validation for transforms, extra fields and collision protection.
Context is available on every LLMAgent form, including literal text with no hooks. It need only be supplied when required input remains after defaults. Template and Script use it as their execution context; Function receives it as its callback argument; LLMAgent shares it between prompt preparation and request/step hooks. Schemas and context settings can be inherited through the same configuration rules.
There is one application context and one input schema. Native SDK Agent entry points spell the same call input options; Casai configuration and .run() use context. Tools additionally require a declared public input schema and may use toolContextSchema for the separate trusted tool-context boundary.
Context
The shared context can contain values, synchronous or asynchronous functions, promises, and other components. In templates and scripts, Cascada resolves asynchronous values when their results are needed:
const orderStatus = create.Template({
template: 'Order {{ id }}: {{ getStatus(id) }}',
inputSchema: z.object({ id: z.string() }),
context: {
getStatus: async (id: string) => `ready for collection (${id})`,
},
});
console.log(await orderStatus({ id: 'A123' }));
These helpers use the same application input and private-binding rules as other components; Cascada adds asynchronous evaluation of the prepared values.
Adding Capabilities with Modifiers
Modifiers are properties of the factory, applied before creating the component: create.LLMAgent.withTemplate(...). Input modifiers select how the main property is prepared; .asStream and .asTool select how the component exposes its result.
.withAudio: Select ordinary supplied-audio input for Transcriber/Translator, replacing inherited media or source preparation. Config supports this direct-input selection too..withText: Select literal input without rendering. It accepts the component's plain input forms, including LLMAgent messages and Embedder string arrays. LLMAgent uses this mode by default..withTemplate: Render inline Cascada text with context, retaining any surrounding native message or image-prompt structure..withScript: Execute an inline Cascada script to prepare the component's input..withFunction: Call a JavaScript function with context to prepare the component's input..loadsText: Load literal text from a named resource through the configured loader..loadsTemplate: Load a named Cascada template through the configured loader, then render it with context..loadsScript: Load a named Cascada script through the configured loader, then execute it to prepare input..loadsAudio: Prepare the selected audio from a path/URL, encoded bytes or a byte stream through the required native backend..asStream: Make an LLMAgent, Template, Transcriber, SpeechGenerator or Translator stream: its calls return a live stream result..asTool: Expose the component as a tool a language model can invoke, while keeping it directly callable.
A modifier changes the type of the main property, not its name, so an LLMAgent's input is always prompt. With .loadsText, .loadsTemplate or .loadsScript, that value is a resource name resolved by the configured loader. With .loadsAudio, it is a media path/URL or supplied encoded bytes/byte stream handled by the native preparation backend.
Text and Template Modifiers
Use a template when the input is text with variables, helper calls, or includes. Configured context supplies private bindings and explicitly declared public defaults. inputSchema parses caller data merged over those public defaults; other configured bindings stay outside validation. Here language is a private configured binding, so callers supply text but cannot override language:
const translate = create.LLMAgent.withTemplate({
model,
prompt: 'Translate to {{ language }}: {{ text }}',
context: { language: 'Spanish' },
inputSchema: z.object({ text: z.string() }),
});
console.log((await translate({ text: 'Good morning' })).output);
Inline multimodal templates use the SDK's own prompt shapes. Casai renders their text fields and retains image/file parts, masks, roles, order and metadata. For an LLMAgent, put the new message in prompt:
const inspectPhoto = create.LLMAgent.withTemplate({
model: visionModel,
inputSchema: z.object({ focus: z.string() }),
prompt: [{
role: 'user',
content: [
{ type: 'text', text: 'Describe {{ focus }} in this photo.' },
{ type: 'image', image: new URL('https://example.com/photo.png') },
],
}],
});
const description = await inspectPhoto({ focus: 'the furniture' });
Only text in the selected template source is rendered. Attachments, tool arguments/results, application data and existing messageHistory stay literal. Native .generate()/.stream() calls also keep their conversations literal. Loaded templates still load a string; a script/function preparer can combine a rendered Template with attachments when needed.
Script and Function Modifiers
Use a script for a preparation workflow, or a JavaScript function for logic such as formatting, fetching data, or calling an API. The function may be asynchronous. It receives the prepared context; the execution-metadata API exposes options such as abortSignal through that context's _toolOptions property:
const summarize = create.LLMAgent.withFunction({
model,
inputSchema: z.object({ paragraphs: z.array(z.string()) }),
prompt: ({ paragraphs }) => `Summarize this document:\n${paragraphs.join('\n\n')}`,
});
const summary = await summarize({ paragraphs: ['First paragraph.', 'Second paragraph.'] });
For an LLMAgent, scripts and functions can return text, a single model message, or message arrays that retain roles, tool messages, and media parts. Their returned text is not templated again. Inline templates can render text within one or more native messages; standalone Template produces text.
Forward the preparer's signal when fetching input:
const summarizeDocument = create.LLMAgent.withFunction({
model,
inputSchema: z.object({ documentId: z.string() }),
prompt: async ({ documentId, _toolOptions: { abortSignal } }) => {
const response = await fetch(`https://example.com/documents/${encodeURIComponent(documentId)}`, {
signal: abortSignal ?? null,
});
if (!response.ok) throw new Error(`Document request failed: ${response.status}`);
return `Summarize this document: ${await response.text()}`;
},
});
The same context._toolOptions property is available to specialized function preparers, such as those opening audio. Casai checks cancellation before starting the backend; external work must cooperate with the signal.
Combining Modifiers
Use modifiers in this order:
- At most one input modifier (
.with...or.loads...). - Optional
.asStreamon LLMAgent, Template, Transcriber, SpeechGenerator or Translator, or.asToolwhere a completed tool result is available. Never combine the two.
For example, create.LLMAgent.withTemplate.asStream(...) streams an ordinary agent; create.LLMAgent.withTemplate.asTool(...) exposes a generation-only tool. .asStream and .asTool cannot be combined on any component, including through inheritance or Config.
Two input modifiers cannot be combined. Script and Function have no .asStream because their schema declares whether they return a stream. Ordinary audio tools can collect one native streaming execution to return a completed value; they never combine .asStream with .asTool. An indefinitely open input cannot produce a completed tool result.
Unsupported combinations have no corresponding factory property; TypeScript reports them and JavaScript sees undefined.
Input and Output Validation
Matching configured values, including inherited values, satisfy required fields on ordinary and tool calls. Declare the complete application input schema; Casai accounts for configured defaults when determining which call arguments are optional. Public arguments override bound tool-context defaults, which override configuration, before the combined input is parsed.
When an argument is missing, inputSchema validates the selected configured application value, overlaid by a bound tool-context value when present. A supplied argument replaces that fallback before validation. For configured numeric factor: 3 without a context override, omission validates 3, supplying 5 validates 5, and supplying 'bad' fails. Parse completed application input together so cross-field checks and transforms work normally. Unrelated configured/context dependencies remain outside this parse. Casai does not filter caller extras before parsing; it rejects retained private collisions afterward, including keys introduced by transforms. Binding creates a new descriptor for fixed defaults without changing the component; it preserves parsed public SDK arguments and native approval behavior.
The shared configuration and returned-value reference define schema settings and result shapes. Optional toolContextSchema validates the separate trusted-tool input described in tool execution context.
Every schema boundary uses its produced value: input, trusted context, output, or stream element. Defaults, stripping, coercions, and transforms affect the invocation; Casai does not write parsed results into shared configuration or caller context. Resolve named configured public defaults and call/model arguments before one input parse. Other configured bindings stay outside the parser, so unrelated inherited values survive a strict input schema. Reject retained private-name collisions before ordinary context merging; no second author-written input schema or silent private-value restoration is needed. Producers/configuration use schema input types where retained; implementations/consumers use output types and ordinary merge precedence. Explicit native SDK tools retain their output-based context typing, including erased raw-input limitations.
Explicit SDK Output and tool objects retain native interfaces, parsing, and transformations. Casai does not rewrite hidden schemas or reparse their results. Casai's own preparation and execution leave supplied context, nested data, configured values, and shared defaults unchanged; native parser behavior, including .readonly() freezing, is preserved as described below.
Custom schema callbacks must be pure: check or compute a value without changing data they receive, changing shared data, or performing external operations. This applies to validators, refinements, preprocessors, transforms, and default/catch factories. If a transform changes an object or array, return a new one. Copy any nested object you change as well; unchanged parts can stay shared:
const profileSchema = z.object({
profile: z.object({ name: z.string(), city: z.string() })
.transform(profile => ({
...profile,
name: profile.name.trim(),
})),
});
// Do not assign to profile.name inside the callback.
Ordinary Zod object/array parsing already creates new containers, so Casai does not copy them again. Some values can still be shared, including clients, values accepted without structural parsing, and objects returned by schema defaults. Casai preserves the SDK/Zod parser's behavior: .readonly() can freeze a shared input or default, and the installed Zod 4 can also freeze an invalid input before reporting a validation error. Native SDK Agent has the same behavior. Casai adds no copying or schema restrictions to prevent it. To avoid freezing shared defaults, return a fresh object, such as .default(() => ({ enabled: true })); create fresh nested objects too if those will be affected. Custom callbacks, including validators supplied through SDK schema interfaces, must still leave received/shared data unchanged and return replacements for changes.
Private binding protection is separate from JavaScript freezing. Object.freeze(toolContext) prevents changes to that container's own properties, but does not freeze nested objects, disable a database client's operations, or prevent a new merged object from containing an attacker-supplied replacement. Casai's private-argument checks remain necessary. Do not treat a frozen input as proof that a Cascada managed copy is read-only, either. No automatic deep-freezing of application contexts or clients is part of this contract.
Casai application context schemas accept and produce objects. Templates/scripts support object schemas with refinements and object-producing transforms, including async parsing, as well as SDK object schemas with validators. Configured default selection still requires discoverable raw field declarations. JSON Schema metadata alone does not supply runtime checking. Script/Function output schemas may describe primitive, array, object, or declared stream results. Without an output schema, a Script result is typed as unknown, since its source can return arbitrary JavaScript values; Function instead infers its callback return. Zod is re-exported as z from casai as well as being available from zod.
Casai schemas support Zod 4 Classic/Mini, SDK schemas, lazy SDK schemas and Standard Schema. Direct Zod 3 schemas are rejected. Native third-party tools and SDK Output specifications retain the SDK's schema support. Local validation does not itself require JSON metadata; configured public defaults need discoverable input-field declarations, and model tools also need JSON Schema metadata.
Configuration may supply some required fields and the call supplies the rest. Resolve those values using the existing merge rules, then validate the merged application context once:
const welcome = create.LLMAgent.withTemplate({
model,
prompt: 'Welcome {{ name }} in {{ language }}.',
inputSchema: z.object({ name: z.string(), language: z.string() }),
context: { language: 'English' },
});
await welcome({ name: 'Ada' }); // Configured language satisfies the schema.
await welcome({ name: 'Ada', language: 'French' }); // Call-time override.
// welcome() is a type error: name is still required.
The shorthand caller and .run({ context }) use the same input types. A supplied field must match inputSchema; a required schema field may be omitted when resolved configuration supplies it. Inherited values count too. Unrelated configured dependencies do not become caller parameters or caller requirements. For a strict schema requiring numeric value and factor, configured { factor: 3, db } permits { value: 2 } and { value: 2, factor: 5 }, rejects a string factor, still requires value, and rejects a caller-supplied db. An open schema retains its extra-field types for unrelated names; the composed caller signature must reject identifiable private collisions without making configured dependencies public. Execution settings such as abortSignal remain outside .run()'s application context.
For example, a schema can convert a string without modifying the caller's object:
const increment = create.Function({
inputSchema: z.object({ count: z.string().transform(Number) }),
execute: ({ count }) => count + 1, // count is a number here.
});
const supplied = { count: '2' };
console.log(await increment(supplied)); // 3
console.log(supplied.count); // Still the original string '2'.
Ordinary calls and .run() resolve source maps, parse final application input, and execute with the produced values plus private/trusted bindings. Do not merge raw schema-governed defaults back afterward. SDK compatibility methods and calls without an effective prompt skip source loading/rendering, but still prepare and validate application context. History alone does not skip a configured prompt. Casai owns this context preparation before model dispatch.
Each immutable binding pairs its descriptor with the raw incoming context used to select public defaults. Its schema awaits asynchronous preparation when necessary; a separate binding may have a different descriptor. Parsed public input enters native records, UI history, and subsequent model requests. Other configured bindings are never automatically copied there, even for open schemas. A retained extra field remains public input and cannot replace a private binding; the tool execution context contract explains absent optional names and runtime declarations. The original component schema and shared tool definitions stay unchanged.
The tool descriptor also annotates supported JSON-valued public defaults with JSON Schema default when their effective source is configuration. A bound-context override prevents advertising the configured value as the fallback; private and incoming context values are never added as default annotations. This does not run application validation, certify an invalid configured placeholder, or modify the original schema in .config.
Making a configured argument omittable removes it from the advertised schema's required list while leaving it available for overrides. This can make a previously compatible schema fail a provider's strict mode: OpenAI strict schemas require all properties to be required. Use a compatible non-strict setting for omission-based configured defaults. Casai preserves your strict setting and the provider's errors; it does not silently remove overrideable fields or change the setting.
Configured public defaults remain subject to the final merged parse: an omitted argument can expose an invalid placeholder, while a valid override can repair it. Explicit { language: undefined } replaces the configured public entry before parsing, allowing a schema default to apply or a required schema to reject it. An undeclared configured db, including undefined, stays outside that parser and cannot be replaced by a retained public extra. Explicitly declare db in inputSchema to make it public and overrideable.
Direct calls can select defaults from declared fields in a one-level union of object schemas. Casai reads the branch field names without choosing a branch before validation. Union tools support private dependencies, but public defaults that require projecting a union tool schema are unsupported. Local validation without configured defaults does not require declaration discovery.
Default-aware tool projection supports independent object-root requirements. Unsupported root composition, references, or property-presence/count constraints fail before execution; asynchronous metadata can defer this error until first use. If projection removes a root required field, schemas containing $ref in any schema-valued position are unsupported, including nested or recursive references. Literal $ref keys in data are unaffected. Nested references remain supported when the root required list is unchanged and the root constraints are supported. The restriction applies only when Casai projects a schema for configured declared defaults, not to unchanged native SDK tools. Provider strict-mode constraints still apply. In particular, OpenAI's strict function schemas require every property to be required, which conflicts with optional/defaulted fields even in native SDK tools. Casai preserves native behavior without nullable sentinels or a strict-mode workaround.
Approval continuations revalidate public arguments with the current tool configuration. Keep declared configured defaults stable for the same approval: changing a default can prevent execution with an SDK tool-error result even while the model continues. Rebuilding a tool with the same public defaults and different trusted toolsContext is supported. Request-specific trusted values belong there; public application inputs can remain public. Casai does not rewrite history to bypass native approval validation.
SDK UI helpers validate history against agent.tools before invoking the agent or its prepareCall. For approval continuation, configure the matching public defaults on the agent passed to the helper; changing them only in prepareCall is too late. A mismatch can reject the UI request before the agent runs.
A default factory is a function such as .default(() => []) that creates a fallback value. SDK/Zod conversion can evaluate pure default factories while building the tool's JSON Schema description, as well as during parsing. Do not rely on a factory running only once or only when a tool executes. Casai does not trial-parse incomplete configuration to discover fields or defaults, and metadata conversion must not supply cached invocation context. The actual call still parses its final merged input and uses that result.
Casai-owned direct, .run(), and injected-runner argument failures reject with ValidationError, retaining the validation cause; Cascada may wrap that rejection through its normal script/render error path. Actual SDK tool validation keeps native SDK errors such as InvalidToolInputError. Callback execution errors retain their native behavior.
Script/Function schema parses completed values and returns the produced result. Stream schemas parse elements lazily in the existing consumer pass and forward parsed elements. Application context is prepared before prompt rendering and prepareCall; both preparation hooks receive its parsed values. Reuse SDK/Cascada parsing already performed for that same boundary rather than adding another pass. See shared output schemas.
When migrating a schema-less component that accepts arbitrary template variables, use an open schema to retain unrelated inputs. A plain z.object({ name: z.string() }) strips an undeclared extra at runtime, and closed-shape call types reject it. z.looseObject preserves it:
const greeting = create.Template({
template: 'Hello {{ name }}! {{ extra }}',
context: { name: 'World' },
inputSchema: z.looseObject({ name: z.string() }),
});
await greeting({ name: 'Ada', extra: 'Welcome.' }); // Hello Ada! Welcome.
await greeting({ extra: 'Welcome.' }); // Hello World! Welcome.
Declare only fields intended to be public: an open schema still cannot replace an undeclared configured dependency. Use a stripping or strict schema instead when dropping or rejecting unrelated fields is intentional. Collision diagnostics identify protected key names, never their configured values; those names must not contain secrets. Supplying the same value as a private binding is also rejected, avoiding an equality-based guessing channel.
Context parsing and rendering failures reject before model execution. Stream elements are parsed as they are consumed; a failure ends iteration after any valid prefix. Native streams retain Cascada's error behavior, and complete returns fail rather than exposing a partially failed value. Casai does not deep-clone arbitrary JavaScript data; schema callbacks must leave shared values unchanged.
Prepared inputs are checked against the selected operation: model messages for LLMAgents, text or text arrays for Embedder, audio for transcription, and so on. Binary and live-stream inputs retain their native values.
Share configuration
A Config groups the settings components have in common. Derive specialized components without changing the shared configuration.
Config groups the shared configuration properties and compatible operation settings for reuse. Pass it as the second factory argument to inherit them:
const defaults = create.Config({
model,
maxOutputTokens: 500,
context: { language: 'English' },
});
const summarizer = create.LLMAgent.withTemplate({
prompt: 'Summarize in {{ language }}: {{ text }}',
inputSchema: z.object({ text: z.string(), language: z.string() }),
}, defaults);
const shortSummarizer = create.LLMAgent.withTemplate({
maxOutputTokens: 150,
}, summarizer);
console.log((await shortSummarizer({ text: 'A document to summarize.' })).output);
A Config can be partial. Children supply fixed configuration requirements; the ordinary call supplies operation inputs it accepts, such as an unconfigured source, required context fields, or streaming audio format. A finished callable must already have fixed settings such as required registered-tool context. Overrides apply to one invocation. Components can inherit from compatible components, using their original .config rather than projected SDK tool properties. Local settings take precedence according to these rules:
| Property | Inheritance behavior |
|---|---|
context, filters, tools, toolsContext |
Merge by key; a child entry replaces the same parent entry |
loader |
Try child loaders first; raceParent(...) tries both together and overrideParent(...) uses only the child. See combining loaders. |
| Streaming mode on LLMAgent, Template and audio components | Inherit from the parent; .asStream enables it and no modifier disables it |
Other properties, including model, prompt, schemas, output, renderOptions, and providerOptions |
Replace the whole value |
Key merging is shallow. A child context: { settings: { language: 'French' } } replaces the entire inherited settings value. A toolsContext entry similarly replaces that tool's whole context value.
Omitting a property inherits it. Explicit undefined clears ordinary replacement properties. For merged maps, an omitted, empty, or undefined whole map retains inherited entries; an explicitly undefined entry replaces that entry. Loaders have separate rules. These rules apply to configuration inheritance; in call-time arguments, undefined means not supplied.
Tool definitions merge only by tool name: a supplied definition replaces the whole inherited definition, never its individual fields. A tool entry set to undefined or null removes that tool after resolution. For example, tools: { search: undefined } removes inherited search while retaining other tools. Remove cleared entries before exposing the effective SDK tool registry or passing it to the SDK; infer tool names and required tool context from that same effective registry. This is a tool-registry rule, not a reason to remove ordinary null/undefined application data.
Keep shared fragments compatible with their consumers. A context-only Config can be shared by a Script and an LLMAgent; language-model settings require an appropriate model component. Source/implementation and output settings follow the shared configuration and return contracts. Incompatible inherited properties are rejected along with incompatible local ones.
SDK callbacks stored in Config need explicit parameter or function types: a fragment does not select the component that owns events such as onEnd. The completed component validates inherited callbacks and infers callbacks supplied as overrides. For example, an Embedder's onEnd: event => ... override receives the native embedding event, including its configured runtimeContext type. Schema-driven execute callbacks and function-mode source preparers still infer application context from the fragment's schemas and context.
Inspecting Configuration
Config and every callable component, including Function and tool forms, expose resolved configuration through .config:
console.log(shortSummarizer.config.maxOutputTokens); // 150
console.log(shortSummarizer.config.context); // { language: 'English' }
.config contains original schemas and the unwrapped implementation callback, including .config.execute on Function. Tool forms expose derived SDK-required properties on the callable: their public execute is the SDK tool entry, while .config.execute remains the implementation used by inheritance. Use inheritance or per-call settings instead of mutating a shared component. Set debug: true for configuration and invocation diagnostics.
Shared Execution Rules
- Calls and composition: Every callable has
.run()for named inputs and supported execution settings, with the same result contract as its ordinary call. Put components or application functions in context to call them from workflows. - Invocation isolation: Casai's merging, preparation and execution leave shared configuration and caller data intact. Derive a component or use call overrides to select different settings.
- Effects: Schema callbacks stay pure. Component bodies may operate on authorized application state or perform external effects; sequence effectful Cascada calls with
!. Independent invocations need application-level coordination for shared state. - Modifier inheritance: Every component inherits its parent's modifiers, including through
Config: source mode,.asStreamand.asToolwhere supported.Configalso exposes.withText,.withTemplate,.withScript,.withFunctionand the three.loads…selectors, plus.loadsAudiofor audio owners, followed by compatible streaming/tool modifiers. For example,Config.withTemplate.asTool(...)prepares a reusable tool fragment. An explicit source modifier replaces the inherited source mode; plainConfig(...)preserves it without choosing a default. Select every mode through modifiers:promptType,streamingandasToolare not configuration properties, even when assigned undefined. Internal metadata retains the selection through inheritance and configuration spreads. Same-named fields inside application schemas/context remain data. Streaming and tool mode stay enabled; no reverse modifiers are provided. Unsupported inherited settings are rejected, not silently discarded. A fragment cannot enable both streaming and tool mode. - Configuration unions: A call must work in every possible source mode. An Embedder with configured text/function alternatives supports
embedder()and.run({ headers }); text/template alternatives also accept shared string replacements. You do not need to narrow the configuration before constructing the component. - Streaming: LLMAgent, Template, Transcriber, SpeechGenerator and Translator inherit streaming mode, and
.asStreamenables it. Script/Function declare stream output throughschema; independently invoked components keep their own modes. See streaming. - Tool adaptation:
.asToolexposes completed application output to a model, collecting declared finite streams where necessary. Direct calls retain their normal result and mode. See using components as tools.
Template, Script and Function keep these native value contracts. LLMAgent's non-tool forms additionally implement the SDK Agent and chat UI protocol.
Select reusable source and tool behavior on Config itself. Both agents below render the template and expose a tool interface:
const shared = create.Config.withTemplate.asTool({
model,
inputSchema: z.object({ topic: z.string() }),
prompt: 'Explain {{ topic }}.',
});
const beginner = create.LLMAgent({ instructions: 'Use everyday language.' }, shared);
const technical = create.LLMAgent({ instructions: 'Use technical terminology.' }, shared);
await beginner({ topic: 'solar power' });
await technical({ topic: 'solar power' });
Use tools and delegate tasks
Append .asTool to a supported factory to let a language model invoke it. Supply a description explaining when to use it and an inputSchema describing the model-provided arguments.
An LLMAgent tool remains callable and has .run() and .config, but it is an SDK Tool, not an SDK Agent: it has no Agent id/version or .generate()/.stream() methods. Keep the non-tool agent for SDK UI helpers, and derive a matching .asTool component when the same behavior is needed as a tool. Derivation leaves the original agent unchanged. This separates the SDK's incompatible Agent and function-tool identity contracts.
Every field declared in a tool's inputSchema is model-controlled, including fields a host supplied through SDK options when using the Agent form. To keep an identifier such as userId trusted, remove it from the tool's public schema and supply it through private configuration or trusted tool context. A configured or tool-context default alone does not protect a still-public field.
LLMAgent tool arguments supply its application context. To turn named fields into prompt text, configure .withTemplate, .withScript, or .withFunction (including loaded template/script forms). The application owns that source; a model field named prompt never automatically overrides it. To deliberately use a field as the whole literal prompt, configure a function that returns it.
A plain .asTool uses a configured literal prompt; .loadsText.asTool uses a configured resource name. Both can accept declared context fields for hooks, such as language, or an empty input schema such as z.object({}) when no public data is needed. Their ordinary application calls retain the usual explicit source overrides.
const summarizeTool = create.LLMAgent.withTemplate.asTool({
model,
description: 'Summarize a supplied document in one paragraph.',
inputSchema: z.object({ text: z.string() }),
prompt: 'Summarize this document in one paragraph: {{ text }}',
output: Output.object({ schema: z.object({ summary: z.string() }) }),
});
const assistant = create.LLMAgent({
model,
tools: { summarize: summarizeTool },
stopWhen: isStepCount(5),
});
// A direct component call still returns the full generation result.
const summary = await summarizeTool({ text: 'A document to summarize.' });
console.log(summary.output.summary);
.asTool accepts native function-tool settings such as metadata, strict, inputExamples, toModelOutput, and SDK input hooks, with the SDK's own types and callback protocols. Complete-input hooks receive parsed public input; input-delta hooks retain raw text. Configure approvals through the owning LLM's toolApproval.
For Function, Template and Script tools, providerOptions configures the tool descriptor. For LLMAgent and specialized model-operation tools, it configures the inner SDK operation and is not forwarded to the outer tool descriptor.
When invoked as a tool, an LLMAgent runs generation, checks completion and returns native parsed output. Streaming LLMAgent tools are unsupported. Template tools return text; Script/Function tools retain native result/finite-stream collection. Ordinary LLMAgent tool calls return the full generation result.
Specialized Components as Tools
Configuration and payload are separate. Only schema-declared fields from config.context provide public defaults; bound toolsContext[toolName] defaults override them, and supplied payload fields override both. This shallow merge is parsed by inputSchema. Undeclared context bindings remain private dependencies and cannot be replaced by payload fields. No other configuration fields enter the payload, and payload properties are never merged into configuration. Names such as prompt and model can be application fields without becoming configuration settings. Authored sources and prepared operation inputs are outside this schema boundary.
Every specialized .run() accepts a separate context payload. Plain non-tool shorthand supplies the native source and operation tail; any required payload must already be satisfied by config.context, or supplied through .run({ context, ...settings }). Plain .asTool components also accept their payload directly: embedTool({ input: "hello" }), or embedTool(input="hello") in Cascada. Both forms parse the payload and select its declared native input field. The priority is an explicit invocation source, then the parsed payload field, then the configured source. An object passed to a plain tool is payload; use .run({ prompt: nativeBundle, context }) for a structured authored source. Ordinary calls return the family's application result, including locally completed audio results; registered tool helpers return the tool projection shown below.
In a specialized tool's plain literal form, including explicit .withText, its arguments are the operation input. Template/script/function and loaded executable-source forms take preparation context and keep their configured source/resource. .loadsAudio.asTool also retains a configured source; use an explicit Function/Script workflow for dynamic native resources. .withText also selects literal input when deriving from a rendered parent; writing it explicitly does not discard the model's operation arguments. The tool result goes to your application and the chat UI, and toModelOutput supplies the model-facing representation. Media results use native content parts where supported, rather than turning success into a fixed string:
| Component | Tool arguments without a modifier | The model receives | The application and UI receive |
|---|---|---|---|
| LLMAgent | Declared application input | Completed text/JSON | Completed text or parsed structured application value |
| Decision | { state } |
Decision answers | Decision answers |
| Embedder | { input }, a string or string array |
Vectors | Vectors |
| Reranker | { query }; candidates come from documents or a preparer |
Native { originalIndex, document, score } ranking entries |
The same entries |
| ImageGenerator | { prompt } |
The generated images, as image content | Images as { mediaType, base64 } |
| VideoGenerator | { prompt } |
Video file content where the calling model supports it | Files as { mediaType, base64 } |
| Transcriber | Plain tools: { audio } containing a URL parsed to native URL; .loadsAudio.asTool: declared context with configured audio |
Transcript text | Transcript text, segments, language, and duration |
| SpeechGenerator | { text } |
Native audio file content using SDK media information, subject to receiving adapter/model support; optional formatting | Serialized audio; the collected-stream path also retains its emitted format/rate |
| Translator | Configured recording with an empty schema, or an explicit preparer/resource input | Translated text by default; optional toModelOutput packages known-format audio |
Completed source/translated text, serialized audio and optional duration |
Multimodal tool schemas
Use supported schemas to declare media properties, including mixed text/media objects, optional fields and arrays. For encoded JSON data, MIME metadata describes the value:
const mediaSchema = z.object({
image: z.base64().meta({ contentMediaType: 'image/png' }),
audio: z.base64().meta({ contentMediaType: 'audio/wav' }),
video: z.base64().meta({ contentMediaType: 'video/mp4' }),
});
These fields can be used in inputSchema, or in the returned-value schema of Script/Function. The SDK's JSON Schema conversion preserves their MIME and base64 metadata. Use ordinary .optional(), z.array(...) and nested objects for other shapes. MIME metadata describes the bytes; it does not decode or certify their file contents. A URL uses z.url(); a host File can use z.file().mime('image/png') or the corresponding audio/video MIME type. The calling model and its native protocol must support the actual input representation. Schema annotations do not make the model generate binary media or resolve attachments.
Map returned media to native content using toModelOutput. This keeps the structured result for the application and gives the model actual image content, where its adapter/model supports it. Here pngBase64 is supplied by the application; the model supplies only the caption:
const captionedImage = create.Function.asTool({
description: 'Return the available image with a caption.',
context: { image: pngBase64 },
inputSchema: z.object({ caption: z.string() }),
schema: z.object({
caption: z.string(),
image: z.base64().meta({ contentMediaType: 'image/png' }),
}),
execute: ({ caption, image }) => ({ caption, image }),
toModelOutput: ({ output }) => ({
type: 'content',
value: [
{ type: 'text', text: output.caption },
{ type: 'file', mediaType: 'image/png',
data: { type: 'data', data: output.image } },
],
}),
});
Audio/video use the same native file-content structure with their actual media type and accurate encoding. A base64 field left in ordinary JSON is not automatically interpreted as media. Explicit SDK tools retain their native outputSchema; Casai has no universal setting by that name. LLMAgent's native structured output is separate from generated files; a JSON schema property does not capture those files.
Some language models generate images as native media parts alongside text. Ordinary LLMAgent results retain those files in result.files. For a tool that returns both data and media, use Function.asTool: call the agent once, select its output and files, and supply a toModelOutput that maps the returned files to native content. The application chooses its result shape and any validation. Casai does not strip media fields from the model schema or insert generated files into structured output.
Here mediaModel supports native media generation. The receiving model must also support the returned file types:
const mediaAgent = create.LLMAgent({ model: mediaModel });
const generateMedia = create.Function.asTool({
description: 'Generate the requested media.',
inputSchema: z.object({ prompt: z.string() }),
schema: z.object({
text: z.string(),
files: z.array(z.object({ base64: z.base64(), mediaType: z.string() })),
}),
execute: async ({ prompt }) => {
const result = await mediaAgent(prompt);
return {
text: result.text,
files: result.files.map(file => ({
base64: file.base64,
mediaType: file.mediaType,
})),
};
},
toModelOutput: ({ output }) => ({
type: 'content',
value: [
{ type: 'text', text: output.text },
...output.files.map(file => ({
type: 'file' as const,
mediaType: file.mediaType,
data: { type: 'data' as const, data: file.base64 },
})),
],
}),
});
Native result.files and provider tool results are distinct. OpenAI's built-in image-generation tool in @ai-sdk/openai@4.0.108 puts its images in provider tool results. An application Function tool can inspect ordinary result.toolResults and deliberately select such media. A formatter on an LLMAgent tool receives only its completed text/structured value and cannot recover omitted files or provider receipts.
Casai forwards native media and preserves native errors and warnings. Working media routes must actually deliver the content. Some current adapters instead warn and drop files or stringify them; Casai cannot universally detect or repair this inside an opaque adapter. Those routes do not provide supported native media delivery. See media tool compatibility for inspected behavior. The SDK has no portable tool-result modality capability query: supportedUrls controls URL fetching, not tool-media support. The native adapter can reject a known unsupported representation before making its HTTP request; otherwise the provider may reject it. MIME annotations alone do not justify rejecting a reusable JSON schema, and a generic wrapper cannot verify how every third-party adapter serializes its input.
Tool arguments are JSON. A model can send a prompt or available URL/reference, but media returned by one tool is not automatically attached to the next tool call. Explicit preparers can accept any schema-declared application payload and resolve it using trusted application dependencies. Casai adds no media registry or implicit uploads.
Media support must exist in both the receiving model API and its SDK adapter. The dedicated image, speech and video generation operations do not themselves run a tool loop; their script/function preparers can call registered tools. Use LLMAgent for a language-model operation that supports media generation and tool calling in the required combination. Its tool result remains the completed text or structured value. A custom toModelOutput replaces the component default and receives that tool value; explicit composition can call a base formatter. An application Function tool may instead return selected media from an ordinary agent call. No extra model execution or media store is needed.
Media tool compatibility
Media content types alone do not establish working delivery to a model. The following adapter observations are version-specific; they do not constitute a runtime capability catalog.
| Adapter | Observed tool-result handling | Audio/video implication |
|---|---|---|
@ai-sdk/anthropic@4.0.96 |
Retains inline images/PDFs; warns and drops inline audio/video file parts | Inline audio/video delivery is unsupported |
@ai-sdk/openai@4.0.108, Chat |
Stringifies tool content, including base64 | Native media delivery is unsupported on this path |
@ai-sdk/openai@4.0.108, Responses |
Maps images to input_image and other files to input_file |
Tested gpt-6-luna route rejects audio/mpeg tool output with HTTP 400 |
@ai-sdk/google@4.0.111, Interactions |
Retains images; warns and drops audio/video tool files despite API support | These audio/video routes require an adapter correction |
@ai-sdk/google@4.0.111, generateContent |
Retains inline audio/video in function responses on native model paths supporting response parts | Both gemini-3.1-flash-lite and gemini-3.8-flash identified the spoken color and number in two different MP3 (audio/mpeg) tool results without receiving transcripts |
The table records inspected behavior; it is not a promise to certify every adapter version or repair unsupported routes. Choose an adapter/model route verified for the actual media format. A custom formatter can deliberately return text or an application reference instead. Schema metadata does not grant media transport, and no generic Casai preflight can promise an error for an adapter that silently discards content.
Tool operation arguments
Model arguments supply operation input or preparation data, rather than an SDK settings envelope. A plain specialized tool's schema declares only its documented operation input fields, such as prompt, audio, query, or Embedder's input. The parsed field must supply the native input, or the component must configure a fallback source. For example, optional { input } needs a configured Embedder input or a schema default; an ImageGenerator can use configured images without a prompt. A transform that removes the field needs a fallback too. Field-value transforms remain available, such as trimming prompt or converting a plain Transcriber tool's URL string into a native URL. That route retains the SDK download hook and its protections; .loadsAudio uses separate native media loading. Custom argument names use an explicit preparer:
const draw = create.ImageGenerator.withFunction.asTool({
model: imageModel,
description: 'Generate an image from a description.',
inputSchema: z.object({ description: z.string() }),
prompt: ({ description }) => description,
});
Loaded-text tools retain their configured resource. Declared arguments may be used by native tool callbacks such as toModelOutput, even when the loaded text is fixed; use a closed empty schema when no public data is needed. These fields do not become resource-name or model-settings overrides.
Plain schemas cannot declare settings such as n, size, topN, model or providerOptions; application-call positional parameters do not publish those settings to the model. To expose a model-selectable setting, use an application Function tool that validates the public choice and maps it to the operation's .run() call.
The model receives images as image content in the tool result, so no prompt rewriting is needed. Anthropic models and OpenAI's Responses API read such images; providers that can't read images in tool results reject or flatten them, and the SDK has no capability flag Casai could check in advance. For those models, set the SDK tool option toModelOutput, which .asTool accepts, to return text instead.
Transcription tool results contain only text, segments, language, and durationInSeconds. Provider responses, headers, warnings, and provider metadata remain available on ordinary native results, but are excluded from tool results and their UI history.
Base64 image/audio results can make saved and replayed UI history large. Image content may also be sent to the model again when that history is replayed. toModelOutput changes the model-facing form, not the execution result stored in the UI. For media storage or delivery, an application Function tool can store native generated bytes and return a reference or URL instead:
const makeIllustration = create.Function.asTool({
description: 'Create an illustration and return its stored URL.',
inputSchema: z.object({ prompt: z.string() }),
context: { illustrator, mediaStore },
execute: async ({ prompt, illustrator, mediaStore }) => {
const result = await illustrator(prompt);
return Promise.all(result.images.map(async image => ({
mediaType: image.mediaType,
url: await mediaStore.put(image.uint8Array, { mediaType: image.mediaType }),
})));
},
});
mediaStore is your application storage service. Returning URLs reduces the JSON history payload; it does not remove model image-processing costs if your formatter still supplies image content. For editing an uploaded image, prefer named attachment arguments and a preparer that resolves them to native image input. Native JSON-compatible encoded-image inputs also remain possible where the schema permits them; ordinary JavaScript callers can pass native bytes directly.
An LLM exposed as a tool must finish its own workflow within that tool execution. If it pauses for an inner approval, a client tool without execute, or a deferred provider result, the tool adapter rejects and the outer SDK records a tool error. The adapter exposes neither the inner history nor its pending approvals to the outer agent. Such tools are allowed because the pending path may never be taken or approval may be automatic. If the application must manage an inner pause, invoke that agent directly and retain its result/history for explicit continuation.
Components selected with .asStream cannot also be tools. Ordinary Transcriber, SpeechGenerator and Translator tools return completed results, collecting native streaming internally when the resolved request shape selects it. LLMAgent tools use generation only, and Template tools return complete text. Script/Function schema-declared stream results are collected. VoiceAgentBackend has a separate session lifecycle and no implicit collection adapter. Plain SDK tools also work in an LLMAgent's tools map.
An SDK tool can yield preliminary results from an async generator. When called through a coded component's injected tool wrapper, a directly returned generator is consumed once and returns its final yielded value, following the SDK convention. Explicit SDK tools retain native result normalization, including the installed SDK's treatment of a promise resolving to an iterable as a single final value. Casai component tools require a declared stream kind: text joins into a string, and elements collect into an array. They reject an undeclared root async iterable instead of returning it to the SDK or guessing how to collect it. Progress updates are not collected into application data.
Calling Tools from Coded Components
Template, Script, and Function call reusable operations as normal context methods. An LLMAgent can expose the same implementation as an SDK tool, allowing the model to choose when to call it. Native components need only the callable helper in context:
const numberInput = z.object({ a: z.number(), b: z.number() });
const multiplyNumbers = create.Function({
inputSchema: numberInput,
execute: ({ a, b }) => a * b,
});
const calculatorSettings = {
inputSchema: numberInput,
context: { multiply: multiplyNumbers },
};
const scriptedCalculator = create.Script({
...calculatorSettings,
script: 'return "Product: " ~ multiply({ a: a, b: b })',
});
const codedCalculator = create.Function({
...calculatorSettings,
execute: async ({ a, b, multiply }) => `Product: ${await multiply({ a, b })}`,
});
console.log(await scriptedCalculator({ a: 6, b: 7 })); // Product: 42
console.log(await codedCalculator({ a: 6, b: 7 })); // Product: 42
const multiplyTool = create.Function.asTool({
description: 'Multiply two numbers.',
}, multiplyNumbers);
// Supply tools: { multiply: multiplyTool } to an LLMAgent.
A Template can use the same helper in {{ multiply({ a: a, b: b }) }}. Helpers can also be grouped under context: { helpers: { multiply: multiplyNumbers } } and called as helpers.multiply(...).
Component context inputs use one object with named fields. JavaScript and Cascada both accept object literals; Cascada also accepts keyword arguments. For a component supplied directly in context, either Cascada spelling works:
lookupOrder({ orderId: 123, quantity: 2, accountId: 1 })
lookupOrder(orderId=123, quantity=2, accountId=1)
Both pass the same named data. Use one spelling per call: keywords supply the whole context object, so combining them with a positional context object, as in lookupOrder({ orderId: 123 }, quantity=2), is rejected rather than merged. Fields are matched by name, optional fields can be omitted, and schema/property order has no calling semantics. Casai does not expand input fields into positional arguments such as lookupOrder(123, 2, 1). The input schema decides which fields are rejected, stripped, or retained. An implementation receives the ordinary merge of configured bindings and parsed input, as described below.
Existing positional main-input, source, context, and history forms remain unchanged. For example, a Template still accepts (template, context), and Cascada keyword arguments can supply its final context object: greeting('Welcome {{ name }}.', name='Ada'). Source overrides can also use explicit names: greeting.run({ template: 'Welcome {{ name }}.', context: { name: 'Ada' } }).
Template, Script, and Function also accept configured tools and toolsContext. Required registered-tool context must be configured, directly or through inheritance, so shorthand calls are usable. .run() accepts compatible inputs for one invocation. Each run captures its effective map and creates immutable Casai tool bindings. After context/schema preparation, a fresh shallow context receives wrappers for unshadowed executable tool names. SDK and coded calls in the same binding use the same descriptor: its schema owns default merging/parsing, and its executor owns private bindings and completed output. Casai root streams are collected there; a plain SDK preliminary stream yields only its final value to the coded caller. Different bindings may have different derived descriptors, while component definitions, original schemas, configured context, and shared environments remain unchanged:
The configuration merge rules apply to coded registries too: replacing an inherited tool replaces its whole definition; setting its entry to null or undefined removes it. Removed tools have no injected wrapper or required toolsContext entry. Coded .run() can override context for the fixed tools but cannot change their definitions.
const tools = { multiply: multiplyTool };
// The model decides when to call multiply:
const modelCalculator = create.LLMAgent({ model, tools, stopWhen: isStepCount(3) });
// The script calls it directly, with the same validation and result:
const fixedCalculator = create.Script({ tools, script: 'return multiply(a=6, b=7)' });
A plain SDK tool() with an execute handler works too; without a model caller, it receives a generated toolCallId, an empty messages array, parsed options.context, and the caller's cancellation signal supplied through .run() or an owning SDK tool call. Deliberately configured context properties shadow injected tools, even when their value is undefined, null, or a non-function. Retained caller fields can shadow executable registered names only when explicitly declared public in inputSchema; an open schema does not authorize an undeclared collision. Stripped extras leave the wrapper available. This protection also applies to transform-created names and no-schema input, without reserving every Cascada built-in. Calling a shadowing non-function fails normally, without tool fallback. This does not remove the tool from the model's tool registry; use another registration name if both bindings are needed. Code-driven calls do not apply model approval policies or manufacture chat tool events. A component exposed as a model tool can therefore invoke an approval-gated tool through its injected wrapper without approval; when that inner effect needs human confirmation, require approval on the exposed outer tool.
Function and .withFunction callbacks infer these injected helpers. Casai tool helpers accept raw public arguments, including fields made optional by configuration, and return completed tool values: a string/array for declared streams or an application value for an LLM tool. Calling a component supplied directly in context retains its ordinary result instead. Native SDK tools keep their supported input shapes, including scalar or array arguments; the object-context requirement belongs to Casai components. Tools without a local execute handler have no injected callable.
Putting a component in context instead calls the component itself, with its own validation and full result: an LLMAgent in context returns its full SDK result, while its tool execution returns the completed parsed output. SDK tool execution adds the SDK's argument parsing, execution metadata, and approval lifecycle; see tool execution context.
Tool Execution Context
Casai tools have closed top-level public input. Every public parameter must be explicitly declared in inputSchema. Unknown raw arguments fail before application parsing/preprocessing, including with a stripping z.object. Open-root/catchall tool schemas are rejected, including root z.record schemas; use a named object shape at the root. Dynamic keys belong inside a declared field such as attributes: z.record(z.string(), z.string()). This applies to direct/named calls on the tool component, SDK registration/binding and injected helpers. SDK/Standard schemas need explicit closed object input metadata, with local enforcement independent of provider strict mode. Ordinary non-tool components and native third-party tools retain their schema behavior; toolContextSchema need not be closed.
Use one application inputSchema to declare public arguments. Casai selects declared defaults, merges raw arguments over them, and parses the complete input once. It then combines parsed public values with private bindings and checks for private-name collisions before execution. The closed raw boundary blocks arbitrary top-level injection, including absent private names. Trusted code must still keep nested public data separate from trusted identity and must not deliberately publish private dependencies through prompts/results or public declarations.
Configured values need no separate schema merely to be available to an implementation:
const scale = create.Function.asTool({
description: 'Scale a number by the configured factor.',
context: { factor: 3 },
inputSchema: z.object({ value: z.number() }).strict(),
execute: ({ value, factor }) => value * factor,
});
console.log(await scale({ value: 2 })); // 6
console.log(await scale.run({ context: { value: 2 } })); // 6
// Supplying factor fails because this inputSchema rejects that field.
To make configured factor a public, overrideable input, explicitly declare it in inputSchema. An open schema alone must not turn a private configured dependency into an overrideable model argument. A child's input schema does not validate or restrict the whole inherited context; extra configured dependencies remain available.
For ordinary components with open input, actual private context properties are identifiable without a context schema, including own properties whose values are undefined. Supported existing context declarations can also reserve absent optional names. Types can describe an optional field that is absent at runtime: {} annotated as { userId?: string } does not itself reserve userId during runtime validation. Do not trust an arbitrary public extra as authenticated identity. Represent optional trusted fields at runtime, for example { userId: authenticatedUser?.id }, or declare them in a supported toolContextSchema. Casai does not infer private names from erased types or arbitrary callback code.
Tool strict mode is provider generation control, not a global SDK validation mode. The installed AI SDK does not enable it by default. With strict omitted, its OpenAI Chat adapter omits the field, while its OpenAI Responses adapter explicitly sends strict: false. This differs from calling the Responses API directly, where omission attempts strict schema normalization and may fall back to non-strict mode. Set strict: true explicitly on compatible tools/providers; see OpenAI's strict-mode contract.
Casai's raw argument boundary rejects an undeclared root userId even without provider strictness. Provider strictness does not govern JavaScript/Cascada calls, supplied history, input transforms or later SDK refinement. Local validation and the post-parse private-binding checks remain active independently of the provider setting.
Named configured public defaults participate in input parsing: configured { language: 'en', db } supplies required input language even for {} arguments, without publishing undeclared db. Inherited values work too. Required in complete application input does not mean required from the caller. Immutable per-run binding preserves this behavior when incoming tool context supplies public defaults too. An open schema does not publish private configuration or allow model arguments to replace the private db binding. JavaScript and Cascada can supply non-JSON values where their schemas permit; actual model transport retains SDK/provider constraints.
Casai .asTool configuration accepts optional toolContextSchema. It validates incoming tool context, not config.context. Casai has no contextSchema configuration alias; its SDK descriptor exposes the same schema under the native name. This is a Tool interface property, not an Agent property. Every owner with a tool registry can configure toolsContext and supply per-invocation overrides. Casai owners bind descriptor/context pairs automatically. Direct native SDK integrations supplying public input defaults through context use bindToolContext to create the matching descriptor and raw context, as shown below. SDK history revalidation also checks declared raw names; root keys introduced by a transform cannot be replayed as raw arguments merely because a stripping schema could discard them. The bare tool descriptor supports private-only native toolsContext without binding. Public-input overlap requires explicit binding and can otherwise fail at execution after approval.
Top-level contextSchema is forbidden in Casai factory configuration and reusable Config fragments, including inherited configuration. Types reject it, and runtime construction throws ConfigError directing you to toolContextSchema, even if the wrong key is explicitly undefined or both names are supplied. Native SDK tools inside tools retain their valid contextSchema property. An ordinary application field named contextSchema inside config.context is unaffected.
const contextualScale = create.Function.asTool({
description: 'Scale a number by an application-provided factor.',
context: { factor: 3 }, // Makes the ordinary caller usable.
inputSchema: z.object({ value: z.number() }).strict(),
toolContextSchema: z.object({ factor: z.number() }).strict(),
execute: ({ value, factor }) => value * factor,
});
const scalingDefinition = create.Config({
tools: { scale: contextualScale },
inputSchema: z.object({ value: z.number() }),
script: 'return scale(value=value)',
});
const scalingWorkflow = create.Script({
toolsContext: { scale: { factor: 3 } },
}, scalingDefinition);
console.log(await scalingWorkflow({ value: 2 })); // 6
console.log(await scalingWorkflow.run({
context: { value: 2 },
toolsContext: { scale: { factor: 5 } },
})); // 10
console.log(await scalingWorkflow({ value: 2 })); // Still 6
Here context: { value: 2 } is input to the workflow; the script passes value as the registered tool's public argument. toolsContext.scale is a separate application-supplied input to that tool invocation. The wrapper captures the effective entry for this run and forwards it through the SDK's context channel. It does not assign to scalingWorkflow.config, change contextualScale, or remember factor: 5 for another call. This is explicit argument passing, not persistent tool memory. An LLM can supply the public tool arguments; the application supplies the toolsContext map. A coded workflow can supply both, while keeping their roles explicit.
Required execution configuration must be bound when constructing the finished callable, directly or through inheritance. Reusable Config fragments may remain incomplete. An explicit .run() setting such as toolsContext or abortSignal has its own contract; it is not an application field admitted by inputSchema. Runtime schemas validate effective invocation values, without schema-requiredness probes at creation. Building a callable per request currently creates a fresh Cascada environment and recompiles inline source on first use; compatible compilation sharing is an optional optimization, not a context-sharing guarantee.
An ordinary contextualScale({ value: 2 }) uses configured factor and does not run toolContextSchema, including its defaults. Types require the finished component to supply the dependencies needed for ordinary calls. Registry bindings preserve undefined versus {} and parse incoming context to select public defaults; configured dependencies are not substituted into that schema. Binding preparation is lazy and can validate advertised tools before model selection. SDK input hooks, approval, and execution still validate context independently with the original schema. Casai does not cache parsed context across those native stages. Injected calls through a Casai binding reuse its already-parsed fixed context instead; objects produced by context defaults remain shared and read-only within that binding. Plain SDK tools without a Casai binding retain per-call parsing and their separate options.context protocol.
Casai-owned binding-context failures have a stage-only public error message. The native cause can contain private values and is for trusted diagnostics. This matters on approval continuation too: streaming can emit tool errors before any model request, and UI error handlers may publish their text. Native SDK-owned context validation retains its native behavior.
Source priority is arguments over tool context over configuration. Binding selects named public defaults from configuration and parsed incoming context, then the original input schema parses those defaults plus arguments. Only that schema controls caller admission. Execution combines private bindings with parsed public input without restoring raw names removed by transforms.
For configured factor: 3, bound context { factor: 5 }, and omitted arguments, the effective value is 5; explicit caller factor: 3 produces 3, and explicit 7 produces 7. Configured or bound defaults can satisfy required complete-input fields; making the schema optional is not a replacement for completing and parsing the input. The binding's entire context stays fixed across tool calls and SDK steps. A separate run may create a different binding without changing the component. Native prepareStep context replacement is unsupported for an existing Casai binding; plain SDK tools retain native behavior.
Native SDK registration: a Casai owner binds its registry automatically. To register a Casai tool directly with an SDK agent and also supply incoming context, create the matching pair with bindToolContext:
const scaleByFive = contextualScale.bindToolContext({ factor: 5 });
const agent = new ToolLoopAgent({
model,
tools: { scale: scaleByFive.tool },
toolsContext: { scale: scaleByFive.context },
});
bindToolContext(rawContext) returns a fresh readonly { tool, context } pair and leaves the component unchanged; another pair can bind a different value concurrently. Register both values together and keep the pair fixed for the whole run, including in prepareStep. Here factor is private because it is absent from inputSchema, so a bare descriptor can also accept it through native context. Binding is required when incoming context supplies public defaults; a bare descriptor cannot use incoming context to revise already validated public arguments. context keeps the raw input type. When toolContextSchema transforms its input, the SDK's toolsContext type expects the parsed type, as it does for native transforming tools, so that registration needs a type assertion. A Casai owner receiving the bound descriptor in tools reuses its existing binding and requires the matching pair's context as its toolsContext entry. Use the component itself, not its bound descriptor, as a configuration parent.
Testing tools: to test configured defaults, incoming tool context and validation together, call the tool through an owning Casai component or a mock-model ToolLoopAgent using the matching pair above. Calling tool.execute(input, options) directly follows native SDK executor semantics: it expects already parsed arguments/context and skips argument preparation. Ordinary component calls test ordinary semantics; they do not exercise incoming tool context. No separate public execution helper is needed.
Execution metadata: Function, Script, Template, and .withFunction all read an always-present reserved _toolOptions property from their prepared context. This replaces the separate Casai callback options argument and the old _toolCallOptions variable. Native options.context is flattened into application context and omitted from _toolOptions; the other native execution fields retain their SDK names/types, including optional experimental_sandbox. Ordinary calls have {} or their explicit abortSignal; SDK calls add native toolCallId and triggering messages; injected calls inherit the caller's native options (including signal and sandbox), replacing the ID and using messages: []. Each injected tool selects its own trusted toolsContext entry. These messages are not the result's assembled messageHistory, and SDK runtimeContext is not implicitly forwarded.
Function and .withFunction infer _toolOptions as the shared exported ComponentExecutionOptions type. It is derived from the SDK, with native context omitted and call ID/messages optional because the same callback also handles ordinary calls:
import type { ToolExecutionOptions } from 'ai';
type SDKToolOptions = Omit<ToolExecutionOptions<unknown>, 'context'>;
type ComponentExecutionOptions =
Omit<SDKToolOptions, 'toolCallId' | 'messages'> &
Partial<Pick<SDKToolOptions, 'toolCallId' | 'messages'>>;
Applications normally use the inferred type; reusable helpers can import ComponentExecutionOptions from Casai rather than repeat this definition. Native SDK tool executors still receive the full SDK options type, with required tool metadata and separately typed context.
// factor comes from configuration or tool context.
execute: ({ value, factor, _toolOptions }) => {
_toolOptions.abortSignal?.throwIfAborted();
return value * factor;
}
Casai supplies _toolOptions after application parsing/merging, so it needs no input-schema declaration and cannot be replaced by caller/configured data. It never authorizes skipping validation. The actual execution metadata is not inserted into SDK public arguments/history. Components must not mutate it or its referenced data. Plain SDK tools retain their native execute(input, options) contract, including options.context; the Casai descriptor also receives those native options before adapting them for its body.
Pass selected application fields to another component, for example child({ value }). Forwarding the whole execution context can fail a child's strict schema because it includes private dependencies, _toolOptions, and injected helpers. Returning that whole context can also publish those values, including native messages; tool results should contain the intended application output. No automatic output redaction is implied.
Incoming tool context is not automatically forwarded to an inner registry. A Function bridge can pass it explicitly to a reusable Script or Template through that component's .run() settings:
// pipeline is an existing component with a registered lookup tool.
execute: ({ id, db, _toolOptions }) => pipeline.run({
context: { id },
toolsContext: { lookup: { db } },
abortSignal: _toolOptions.abortSignal,
})
Each call creates its own binding; the pipeline and its compiled source can be reused. An injected tool call itself supplies application arguments, not another tool-context map. Cascada code can likewise call a component made available in its context through .run() when explicit nested settings are needed.
Tool definitions and toolsContext merge by tool name through configuration and supported call overrides. Each supplied tool-context entry replaces that tool's whole context value. SDK tool execution supplies already-parsed arguments/context, and Casai's execute wrapper does not validate them again. Injected wrappers normalize named/keyword arguments, removing Cascada's __hasKeywordArgs marker before validation, then validate once before execution. This also applies to plain SDK tools and strict schemas; direct component calls use the same argument normalizer and their own preparation boundary. Adding or changing tool contracts requires deriving a compatible component.
Tool Approvals and Continuation
Use resume(history, options?) to continue a conversation without loading or rendering another prompt. Supply approval decisions through approve; use the other options for context and supported execution settings. It returns the same SDK result as an ordinary call, including messageHistory.
resume() belongs to non-tool LLMAgents, including .asStream. .asTool components do not expose it; they complete their tool execution and return a value.
An LLMAgent can return control when a tool needs approval or an external result. A larger stopWhen limit does not resolve that pending input. With SDK 7, use toolApproval for an approval policy:
const reviewCalculator = create.LLMAgent({
model,
tools: { multiply }, // The Function tool from the LLMAgent example.
toolApproval: { multiply: 'user-approval' },
stopWhen: isStepCount(5),
});
const pending = await reviewCalculator('Use multiply to calculate 37 times 29.');
const decided = new Set(pending.content.flatMap(
part => part.type === 'tool-approval-response' ? [part.approvalId] : [],
));
const settled = new Set(pending.content.flatMap(
part => part.type === 'tool-result' || part.type === 'tool-error' ? [part.toolCallId] : [],
));
const requests = pending.content.flatMap(
part => part.type === 'tool-approval-request'
&& !decided.has(part.approvalId) && !settled.has(part.toolCall.toolCallId) ? [part] : [],
);
The call returns these requests; it does not remain open waiting for a person. Save this fresh paused step's request list together with its complete messageHistory and raw context/tool-context inputs as one conversation revision. Restore that record to show the requests after a reload or restart. Update the saved list with the history when recording decisions, external results or a later pause: display requests without a recorded decision or result, matching approval selection. Automatic requests normally have decisions; an automatic request missing its decision and result remains selectable. When rebuilding from history, use the active segment and last-write ID lookup described below rather than treating old step content as current state. Collect decisions against the displayed revision. If the user approves all displayed requests, pass their IDs explicitly:
const result = await reviewCalculator.resume(pending.messageHistory, {
approve: requests.map(request => request.approvalId),
});
console.log(result.output);
Before applying a human decision, check the displayed revision against the application's authoritative conversation and coordinate concurrent updates. A stale tab's approve: true can approve new requests the person never saw. Explicit IDs reject resolved/unknown selections, but if the displayed IDs remain pending alongside a new request, the array denies that unseen request. IDs therefore do not replace a revision check. This persistence/concurrency check belongs to the application; resume() adds no revision option or pending-list service.
resume(history, options?) accepts readonly ModelMessage[] and starts a new invocation from saved history without rendering a prompt or adding a user turn. It does not reconnect to a live stream like the SDK UI client's resumeStream(). Its options are:
| Field | Contents |
|---|---|
context |
Application input, merged with configured defaults and validated as usual; required when configuration does not supply the necessary values |
approve |
true approves all remaining requests; false or [] denies all; a readonly ID array approves listed requests and denies the rest; omission, undefined or null supplies no decision |
| Execution settings | Applicable per-call settings such as abortSignal, timeout, tool settings and hooks |
To continue the same paused turn, retain its raw application context and any per-call toolsContext inputs alongside the history, then reuse or reconstruct them for resume. Required renderer fields still need their original values even though rendering is skipped: supply the actual earlier message, not a placeholder that changes what hooks see. Store raw schema input, not parsed hook output, and keep configured public defaults compatible. The application owns this record; Casai does not recover it from history. Reconstruct nonserializable trusted services as needed. Keep approved public arguments and defaults stable; private dependencies may change between requests.
Retain or deliberately reconstruct policy-dependent per-call settings too, such as runtimeContext, toolApproval and tool overrides. For local execution, the SDK re-evaluates policy using the continuation's inputs and messages; its last message may be a tool approval response. Current policy can deny a person's approval and skip local execution while the model still answers. Reconstruct current trusted authorization deliberately; do not treat an old runtime context as proof of continuing permission. Provider decisions need application authorization before forwarding.
Omitting approve, or explicitly passing undefined or null, supplies no new decisions and leaves approval handling to the SDK. Unanswered local approvals normally fail natively; a provider approval can be ignored without sending a decision. Cascada none and an unset decision variable produce null, so an unset variable does not catch a forgotten provider decision. Null never means denial or approval. IDs are approvalId values, not message or tool-call IDs. Repeated selector entries count once; unknown and already-resolved selections reject. These checks interpret the shorthand; they do not validate existing history or guarantee SDK execution. Supplying context or history with results never implicitly approves unrelated work. Per-request reasons can use native SDK messages.
When nothing is undecided, approve: true, false and [] add no decisions and still continue the conversation normally, including any already-approved work awaiting execution. They do not skip the next model step or make duplicate submissions idempotent. A nonempty list containing resolved IDs still rejects.
For results produced by a client or background worker, put native encoded tool-result parts in the final tool message alongside any matching approval responses. Preserve call IDs, tool names and provider metadata. Calls with recorded results need no new approval decision, and Casai does not reformat those results. Supply any tools still needing execution through configuration, supported call overrides or prepareCall.
Cascada keywords supply the options object: agent.resume(history, approve=true, context={ topic: 'x' }). Unlike ordinary shorthand calls, application data must be nested in context: writing topic='x' here makes it a setting and may silently leave the configured topic in use. JavaScript options variables can carry the same mistake. History stays positional; do not combine a positional options object with keywords. Resume options reject prompt, messageHistory, native messages and native options. For a new user message, use the source-appropriate data path described below; rendered agents receive user text through their configured context field.
Resume copies the history array and, when adding decisions, the final tool message and its content array. Other messages, parts, inputs, outputs and metadata remain borrowed: leave them unchanged until the invocation finishes, including stream consumption. Approval selections are consumed synchronously before asynchronous preparation. Casai does not deep-clone or freeze history.
New approval decisions apply to the segment after the last user/system message and exclude already-decided or result-bearing requests. Automatic requests normally have recorded decisions, which exclude them too; an automatic request without a decision or result remains selectable. Casai extends the final tool message when adding decisions, preserving native transport fields, and adds no empty message. It leaves existing message placement and decisions unchanged. Resume adds approval responses; the SDK creates any needed denial results in responseMessages. Empty history alone does not reject: resume([]) still validates context and lets prepareCall supply messages; the SDK rejects if the final conversation remains empty. Hooks can replace messages and tools through their existing contract.
Supplied history follows the SDK's approval and tool-result protocol. Casai adds the requested decisions without repairing existing messages. If definitions reuse an ID, the last request/call definition in the supplied history is used, matching SDK lookup. Missing call definitions follow native validation after hooks, just like other history errors.
resume() generates, or streams on an .asStream component. When saving a continuation, replace stored history with its complete messageHistory, awaiting that property for streaming. Appending only responseMessages loses approval responses and external results supplied as input, including changes to an existing final tool message. The component retains no conversation state. Follow the history and failure guidance when deciding what to save.
A tool may execute before the SDK discovers another missing result or protocol error. Duplicate existing responses or results outside the SDK's lookup window can also lead to repeated execution. Resume supplies no early-rejection or transaction guarantee; the application owns authoritative history, authorization, effect reconciliation and idempotency. Retrying the same pending snapshot can execute again. Reconstruct the approved call's public defaults for later requests; changed effective input can fail SDK revalidation. Private dependencies may change.
JSON storage must preserve the approved parsed input as well as recorded raw input. For example, a parsed Date becomes a string through JSON: unsigned revalidation then returns an input-error result without executing, while signed continuation rejects the changed signature. Prefer JSON-compatible parsed arguments such as ISO strings, converting inside execute, or a verified application-owned type-preserving format. Rich values have different serialization/signing limits; Casai adds no serializer or schema ban.
Inspect responseMessages/messageHistory for incoming approval outcomes. These tools run before the first model step, so step-derived content, toolResults and steps omit their successes, denials and input-revalidation errors. Streaming also exposes full-stream events. A successful native output does not prove the approved operation executed; the model can answer after a handled tool error.
Streaming can repeat tool-output-denied for an already-settled call whose negative response and execution-denied result remain in the final tool message, for example an automatic denial alongside another pending approval. This native event does not mean another execution or a new result. UI/full-stream consumers should reconcile it with existing state by tool-call ID; Casai does not suppress it.
UI stream consumers also need the paused assistant UI message containing those tool-call parts. For server completion callbacks, pass it last in originalMessages to the native UI stream helper; the browser must retain that message too (readUIMessageStream accepts it as message). Server originalMessages does not replay missing parts to an empty client. Without the matching UI state, processing incoming approval outcomes raises UIMessageStreamError: No tool invocation found, even though constructing/serializing a response without callbacks can succeed. If only model-message history is retained, use native stream/text/output consumption. Casai does not reconstruct UI messages from model history.
Every resume starts stepNumber at zero with empty steps; incoming approval results are in prepareStep's messages/responseMessages. A hook forcing a tool on step zero will force it again. isStepCount(n) limits each invocation separately; applications own a budget across continuations.
stopWhen: hasToolCall('submit') cannot end resume immediately after an incoming approved submit: successful continuation still asks the model for a new step, and stop conditions see only the new model steps. An authored step-zero hook can request toolChoice: 'none' when the terminal result is already in messages, asking for a final answer; it still makes a model call. activeTools, toolChoice and tool-caller routing do not revoke already-approved incoming work, and prepareStep runs after it. Current approval policy and service authorization control execution.
Incoming approved tools receive the caller's cancellation signal and SDK total/tool timeouts (totalMs, toolMs and per-tool overrides). stepMs and streaming firstChunkMs/chunkMs start later and do not cover that work. Use tool/total timeouts with executors that honor cancellation; these do not forcibly interrupt tool code, and a handled tool timeout may still let the model answer. Narrowing activeTools does not withdraw approval; denying an undecided request or current policy can prevent execution. Missing executors retain native handling.
Starting a new message while approvals are pending
Call denyPendingApprovals(history, reason?) before adding a replacement user message. This synchronous helper returns a new history array. For each undecided local approval, it adds a negative approval response and a matching execution-denied tool result. For provider-executed approvals, it adds only a negative response with providerExecuted: true. It uses the same active-segment selection as resume. A local denial already recorded in that segment without its result also receives the execution-denied result, keeping the recorded reason, as the SDK's UI message conversion does. Other existing decisions and results are unchanged. It does not execute tools or contact a provider.
The helper accepts readonly ModelMessage[] and an optional string reason for the denials it adds. It copies only the outer array and a final tool message/content array it extends; other objects remain borrowed. Every request it denies or settles needs a matching tool-call definition so the helper can determine the tool name and execution kind; a missing definition raises ValidationError. With nothing to deny or settle, it returns a new outer array without adding any parts.
Other unfinished work still needs to be settled, including external results, already-approved calls awaiting execution and anything left unsettled in an older turn. The helper does not certify that history is ready for a new message, undo effects or stop work already running.
SDK chat UIs that build model messages with convertToModelMessages do not need the helper: that conversion already drops unanswered approval requests before a newer user message and adds denial results for recorded denials. Dropping a request sends no provider denial; see the MCP note below.
For the paused calculator above, when its unanswered approvals are the only unfinished work:
import { denyPendingApprovals } from 'casai';
const settledHistory = denyPendingApprovals(
pending.messageHistory,
'The user sent a different request.',
);
const nextText = 'Explain multiplication without using a calculator.';
const nextResult = await reviewCalculator(nextText, settledHistory);
On a plain text agent, the ordinary call adds the new user message, replacing any configured text. Any non-tool form, including .loadsText, can instead append the message itself: agent.resume([...settledHistory, { role: 'user', content: nextText }], { context: newTurnContext }). This skips rendering and uses the component's generation/streaming mode. Supply the new turn's raw context, including required renderer fields.
When the new message needs configured template/script/function preparation, including loaded templates/scripts, use .run({ messageHistory: settledHistory, context: { ...context, message: nextText } }), with the application's declared field consumed by its preparer. Never pass end-user text as a rendered agent's prompt: that selects executable source, a resource name or a function. These recipes rely on the application to establish the earlier settlement. With a new user message last, the SDK does not synthesize earlier missing denial results, and missing local results are rejected before provider dispatch. See rendering only the new message.
For a pending OpenAI MCP approval, the helper's negative provider response is sent by the subsequent literal or rendered call. Retain provider history/metadata and the provider options used for continuation. The adapter forwards the response as an MCP denial even though the tool message is no longer last. Starting a new user/system turn without a negative response sends no denial and does not establish provider cancellation. Provider acceptance still depends on the saved conversation and available provider state.
OpenAI MCP storage limitation: approval and denial recipes assume the earlier response is available through default/enabled storage, or through previousResponseId referring to an available earlier response. In the installed adapter, a fully stateless store: false continuation sends the decision without the original approval-request item, an item reference or a response-chain ID. This does not reconstruct the prior request as described in OpenAI's MCP guide; provider acceptance of that stateless request is not guaranteed. Do not rely on these recipes for stateless approvals or cancellations. previousResponseId is not a workaround for an unavailable prior response, and ZDR treats storage as disabled. Ignoring an approval sends no decision and is a separate case. Casai adds no provider-specific history reconstruction.
Protecting approval decisions
If approval history passes through a client, configure native experimental_toolApprovalSecret on the originating and resumed calls, or recover authoritative server-held history. For JSON-compatible parsed input, signing protects the recorded operation from forgery; it does not authenticate the human decision or external results, authorize the user/tenant, or prevent replay. Rich parsed values inherit the SDK's hashing and serialization limitations; type-preserving storage does not repair them.
Filtering approve on the server does not restrict affirmative responses already supplied in client history: even approve: [] or false leaves those recorded decisions in effect. For local tools, enforce per-decision authorization in the SDK-rechecked toolApproval policy or the service executing the action. Alternatively, use authoritative server history and accept only authorized new selections. Provider decisions must be authorized before forwarding; the SDK's local policy recheck does not cover provider execution. Signing an operation does not authorize an embedded response.
.run() remains for ordinary calls. During an active invocation, use native async toolApproval/execute callbacks. SDK chat UIs already send complete approval conversations through native Agent methods and do not need resume(); see the SDK approval guide.
Steps, hooks and continuation
An LLMAgent can execute tools during a model step, then use their results in later steps. For example, this agent allows up to five model steps:
import { isStepCount } from 'ai';
const multiply = create.Function.asTool({
description: 'Multiply two numbers.',
inputSchema: z.object({ a: z.number(), b: z.number() }),
execute: ({ a, b }) => a * b,
});
const calculator = create.LLMAgent({
model,
tools: { multiply },
stopWhen: isStepCount(5),
});
console.log((await calculator('Use the tool to multiply 37 by 29.')).output);
Calls and automatic steps
- One
component(...)orcomponent.run(...)call starts one invocation. - Each step calls the model and handles its tool calls. The next step can use their results.
- Execution ends when the model finishes, external input is needed, or a stopping condition prevents another eligible step.
stopWhen is a function that receives the completed steps and returns true to stop or false to allow another eligible step. It may be asynchronous. An array stops when any condition returns true.
The default is isStepCount(20), matching ToolLoopAgent: at most twenty model steps per invocation, unless configuration or call settings select another condition. This is a ceiling, not a request to run twenty steps. Without tool activity or queued steering messages, the SDK finishes after one model step and does not evaluate stopWhen. Both call forms remain valid without tools. Set stopWhen: isStepCount(1) for an explicit single-step policy. See SDK loop control.
The default is supplied before prepareCall, without changing stored configuration. A hook that removes or clears stopWhen selects the core SDK's one-step fallback; Casai does not restore twenty afterward.
Hooks within an invocation
Hooks are application callbacks configured on the component or supplied through supported per-call overrides:
prepareCalladjusts the request once, before SDK execution.toolApprovaldecides whether a requested tool may execute or needs later human approval. An asynchronous decision can be awaited within the current invocation. Denying all requested local tools does not itself prevent the next step; normal stopping rules still apply.prepareStepadjusts each scheduled model step, including the first. For example, it can select a stronger model after earlier steps fail to solve the task.
These callbacks do not restart execution or reset step counts. To continue with a stronger model, let stopWhen allow another step, then select its model through prepareStep. A step hook cannot override a stop condition that has already ended the loop.
Continuing with saved history
component.resume(history, options) starts a fresh invocation without loading or rendering another prompt:
- It uses tool replies already in history and can add approval decisions for pending tools.
- The model can use those results, answer, or request more tools.
- SDK step counts start afresh. There is no separate
promptargument; the supplied history is the conversation. - With settled history and no tools available, resume still makes one new model step. It is not a no-op when nothing is pending.
- Recorded replies can be read without executing their tools again. An approved local call awaiting execution still needs its corresponding tool and executor.
Configuration and per-call overrides
- Component configuration supplies the model,
stopWhen, registeredtools, applicationcontextand per-tooltoolsContext. - Supported call settings can override them. Supply required inputs that configuration does not provide.
.run({ tools: ... })can replace compatible declared tools or remove them. Add new tool names or change their contracts by deriving another component.- Overrides from an earlier call are not remembered. Preserve and supply them again when needed; history does not contain that setup.
- Application objects and callback closures can hold state. Starting another invocation does not automatically reset that state.
New prompt or continuation
component(...) and component.run(...) prepare and append their configured or supplied prompt. component.resume(...) skips that preparation. All use earlier tool replies when their history is supplied.
Without an effective prompt, .run({ messageHistory }) already sends history alone. An unchanged prompt source does not select continuation automatically: the same template can render a different message from new context.
Neither an ordinary call nor resume automatically denies pending tools. Denying a pending approval refuses that execution; it does not discard replies or undo completed work. Starting a separate conversation without old history does not stop external work already running. See tool approvals and continuation for recording decisions before a new turn.
LLMAgents used as tools
- An LLMAgent used as a tool performs its model steps inside one outer tool call, with the same callbacks.
- It returns completed output or fails if it pauses or a stop condition cuts off another eligible step.
- Natural completion on the last allowed step succeeds.
- It exposes no
.resume().
A one-step limit can succeed only if the inner run completes in that step. If a local tool call or deferred provider work makes another step eligible, the limit cuts it off and the tool invocation fails.
Trusted tool context
toolContextSchema validates incoming native ToolExecutionOptions.context; it is exposed as the descriptor's native contextSchema. Do not use top-level contextSchema in Casai configuration. Ordinary calls do not parse config.context through the tool-context schema.
Priority is explicit public arguments, then bound tool context, then configured public defaults. Private dependency collisions remain protected. Bare descriptors accept private-only incoming context. Bind incoming public defaults explicitly:
const lookup = create.Function.asTool({
inputSchema: z.object({ city: z.string() }),
toolContextSchema: z.object({ city: z.string() }),
execute: ({ city }) => city,
});
const bound = lookup.bindToolContext({ city: 'London' });
// Pass bound.tool and the matching bound.context to native SDK tools/toolsContext.
Casai owners bind registered tools internally. Configured public defaults may be advertised as annotations where supported, without publishing private values. The component keeps its original schemas; a tool descriptor can expose a derived public schema. Function tool bodies remain available as .config.execute, while the tool's public .execute(input, options) is the SDK entry point. Binding retains native context-validation boundaries. Approval continuation must use stable defaults; otherwise native revalidation can reject execution.
Making a defaulted tool argument optional can conflict with a provider's strict schema requirements. Use compatible tool schemas and provider settings; Casai does not silently change strict or repair provider errors. Public defaults that require projecting union or reference-based root schemas have additional limits. Ordinary local schemas and unchanged native tools retain their native validation behavior.
Registered tools are also available as callable helpers in Template, Script and Function context. Those coded calls reuse validation and tool context but do not run the model's approval policy. If a model-facing outer tool performs a sensitive action through an inner helper, put the required approval on the outer tool and enforce service permissions where the action occurs.
Bodies and prompt functions receive context._toolOptions: actual invocation metadata such as the tool-call ID, messages, and abort signal. Ordinary calls have no fabricated tool metadata. Input/configuration cannot spoof this reserved field. Native descriptors retain execute(input, options).
Stream and combine results
Concurrency starts independent work sooner. Streaming lets the next consumer use a result before it is complete. Ordinary sequential code can describe both. Completed model results, partial model output and execution events have different guarantees; choose the stream that matches what you need to show or process.
Work in progress: native Cascada
stream/tstreamchannels and Template streaming examples below belong to the planned Cascada streaming integration. LLMAgent and audio streaming, and Script/Function returning JavaScript async iterables, are available now.
Streaming contracts
A component's result-delivery mode is chosen when it is created and inherited by derived components. To choose complete or streaming delivery independently, derive variants from shared Config. .asStream enables streaming on LLMAgent, Template, Transcriber, SpeechGenerator and Translator; the base factory does not disable it. Ordinary audio components may collect native streaming internally according to their input/format contract. Script and Function return what their schema declares. Each invocation executes once, and independent nested components keep their own modes.
| Component | Complete | Streaming |
|---|---|---|
| LLMAgent | SDK generateText result |
With .asStream: SDK streamText result |
| Template | Rendered string | With .asStream: text chunks as the template renders |
| Transcriber | Completed transcript fields | With .asStream: native transcript events and final promises |
| SpeechGenerator | Completed audio and metadata | With .asStream: native audio stream and final metadata |
| Translator | Completed translated audio/text and metadata | With .asStream: native translation events and final promises |
| Script | Returns a value | Returns an async iterable or a native stream/tstream channel declared by a stream schema |
| Function | execute returns a value |
execute returns a stream, declared by a stream schema |
To enable streaming on a supported component in complete mode, derive a streaming component from it: create.LLMAgent.asStream({}, writer).
Cascada native streams have two runtime kinds: tstream for text chunks and stream for elements. Their schemas preserve that distinction. LLMAgent exposes native SDK textStream for live text and output for completed parsed output; Casai adds no final-answer stream filtering.
Streams are consumed as they are read. Passing a stream to a component allows it to consume the stream; returning that same source does not restore consumed items. It may have unread items, be exhausted, or have been closed. A Script, Template, or Function returning a stream adds no replay guarantee. Sharing must be explicitly supplied by the underlying source or a sharing helper. LLMAgent's SDK result getters retain their separate ability to create fresh views of one execution.
Two helpers exported from casai collect a native stream into its complete value: collectTextStream(stream) joins text chunks into one string, and collectStream(stream) collects elements into an array. Both accept any async iterable. Use collectTextStream(result.textStream) to collect all native model text, including intermediate commentary; await result.output for the final step's parsed output. In a Script, assigning a stream or tstream channel takes a snapshot of the elements emitted before that assignment in source order.
Nested calls keep their declared contracts. A Template forwards a child's stream when it streams, and collects it when it renders complete text. See composition.
Cascada shares async iteration between its loops by default. This internal sharing does not make a stream returned to JavaScript replayable.
Cascada's default loop sharing also spans renders that receive the same source object. A later call can replay earlier items and repeat the loop body's external operations. Supply a fresh source for independent runs, or use renderOptions: { replayAsyncIterables: false } for native loop consumption. The source owner can dispose shared history through makeSharedIterable(source).dispose(); disposal permanently ends replay for that source rather than resetting it. Casai does not automatically dispose sources when a render ends, since another reader or returned stream may still use them.
Cascada owns error handling for its complete returns and native stream/tstream types. A complete value is healthy or a poison/failure outcome. A native stream delivers its valid prefix and terminates at its first error; neither the failed nor later items are delivered. Casai forwards this behavior without scanning partially failed objects or choosing different stream semantics for different consumers.
Collectors and tool adapters propagate stream failure instead of returning successful partial results. Casai forwards supported cancellation and closure; Cascada and the SDK own their scheduling and shared-source cleanup. A returned live stream remains usable after the component call resolves.
Use toReadableStream(source) to adapt an async iterable for web/SDK response helpers. Conversion consumes one iterator without starting another component execution. For several readers of a single-use source, wrap the validated stream once with makeSharedIterable, then convert or collect that shared view. The helper retains the sequence until the owner calls .dispose(); cancelling one reader does not dispose the shared source. Disposal is permanent.
Stream Schemas
Zod has no stream type, so casai exports two schema constructors, textStreamSchema() and streamSchema(), for the schema of a Script or Function that returns a stream:
| Schema | The program returns | Collect with |
|---|---|---|
textStreamSchema() |
tstream: an async iterable of text chunks |
collectTextStream(): the joined string, '' when empty |
streamSchema(elementSchema) |
stream: an async iterable of complete elements |
collectStream(): the elements in order, [] when empty |
The schema distinguishes text chunks from list elements and preserves that kind at runtime. It checks a Function producer's return type and validates Script results at runtime. Plain JavaScript async iterables acquire the kind declared by their schema. Native Script channels retain their stream or tstream kind, and a configured schema must agree. Elements are complete values, not partial object updates.
Elements are parsed lazily during consumption: producer, schema parser, then caller. Where needed, one wrapper reads each producer element once and forwards the parsed element, including transformations. Neither a new wrapper nor a new element duplicates producer execution, starts another source reader, or retains replay history. Preparing a wrapper reads nothing. Collection uses that view without reparsing. Reuse parsing already done by the SDK or Cascada for the same contract.
Text schemas parse string chunks; element schemas parse complete healthy elements and forward their schema-produced values. Failures stop JavaScript iteration after the valid prefix. Whole-result checks finish only at completion; guaranteeing whole-stream validity before exposing anything requires explicit collection.
Each component applies its declared schema at its own boundary. When SDK/Cascada performs that same boundary's parsing, reuse its parsed values. A Function forwarding a native stream through a newly declared streamSchema(...) still applies its own schema: z.number().positive() must reject a forwarded -1, and two components each declaring a number-increment transform apply it once each. Forwarding adapters and collectors with no new schema add no validation pass, producer, or replay history.
Stream schemas describe only a whole returned stream; a JavaScript stream nested in a returned object is an opaque value whose elements Casai doesn't validate.
Script/Function .asTool collects schema-declared finite native streams into a completed result: join tstream chunks or collect stream elements. The direct component call still returns its stream. These components have no .asStream modifier. Only a root stream is collected: a result that contains streams inside an object is returned as is, so a component used as a tool must produce a tool-suitable result.
Ordinary Function/Script calls and .run() may also return plain JavaScript async iterables without a stream schema, including through an opaque ordinary output schema. Those values have no declared Casai stream kind. When used as a tool, a root async iterable requires textStreamSchema() or streamSchema(elementSchema); an undeclared one fails with ConfigError without acquiring or reading its iterator. Where retained types prove that result, .asTool rejects it at type-checking time. Nested iterables remain opaque.
LLMAgent uses SDK Output.text() or Output.array({ element }), with its SDK validation and result semantics. Its partialOutputStream remains available for compatibility.
When calling .run() or reading .config from Cascada, expose the component directly as a context binding. The current engine preserves component.run(...), but nested function lookup such as services.component loses the function's attached properties; services.component(...) itself still works.
Template and script sources execute application code with access to their configured context. They are not a sandbox: even a template expression can execute arbitrary JavaScript. Use trusted authored sources, including stored/loaded templates, and pass end-user or model text as context data. Error messages can include values used by a failing expression; sanitize errors before exposing them to a model or browser.
debug: true logs configuration and invocation data without redaction, including headers and private context. Enable it only where those logs are appropriate.
Streaming with .asStream
The .asStream modifier makes ordinary calls and .run() return a live SDK result. Awaiting the call does not wait for completion. Consume textStream for live text or await output for completed parsed output.
const writerStream = create.LLMAgent.asStream({ model });
const textResult = await writerStream('Explain battery recycling briefly.');
for await (const text of textResult.textStream) {
process.stdout.write(text);
}
console.log(await textResult.usage);
Create a streaming LLMAgent when callers need live output or SDK events, such as a chat handler or a streaming Template. To stream an existing LLMAgent, derive one from it with create.LLMAgent.asStream({}, writer). Within a Template or Script, select the child's streaming mode explicitly. Streaming result fields
.asStream follows an input modifier and remains enabled in derived components. LLMAgent tools cannot combine it with .asTool, directly or through inheritance.
Consuming a Stream
Use native output for completed parsed output. For live text, partial structured data or tool activity, select a native SDK stream:
| What you need | Result property | What it delivers |
|---|---|---|
| Live model text | textStream |
Text chunks across model steps, including intermediate commentary. Structured output can appear here as JSON text. |
| Partial structured output | partialOutputStream |
Partial parsed snapshots; they can be incomplete and do not establish final schema validity. |
| Array elements as they become available | elementStream |
The SDK's element stream, when supported by the output specification. It retains native SDK semantics. |
| Execution activity for a UI or custom consumer | stream |
SDK events for text, reasoning, tools, step boundaries, errors, and completion. |
| The SDK's completed parsed output | output |
A promise with native SDK semantics, without an additional Casai completion check. |
For example, explicit Output.text() lets you display live text and then await the final answer:
const writer = create.LLMAgent.asStream({
model,
output: Output.text(),
});
const result = await writer('Explain battery recycling briefly.');
// The live result handle is available; generation may still be running.
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}
const text = await result.output; // Completed final string; the same execution.
In a tool loop, textStream might show "Let me check." followed by "It is 18 C."; native output contains the final step's text. See final-answer streaming in tool loops for an explicit writer phase.
For structured output, await .output for the completed parsed value. An array output gives an ordinary array, so iterate it with for, after awaiting:
const list = create.LLMAgent.asStream({
model,
output: Output.array({ element: z.object({ title: z.string() }) }),
});
const items = await list('Suggest three titles for an article about recycling.');
try {
for (const item of await items.output) {
console.log(item.title);
}
} catch (error) {
console.error('No valid final list is available:', error);
}
Stream consumption drives completion. Read a stream, forward an HTTP response, call consumeStream(), or await output, usage or steps. Each native stream handle keeps its consumption and locking rules. These views reuse one execution and parsed output; accessing the result again does not reset a custom iterator returned by its parser.
Native SDK streams retain their error behavior. textStream omits error event parts, so finishing that loop alone does not prove success. Observe callbacks or stream errors and inspect finish reasons. Transport or iterator failures can still throw.
Output schemas must be pure and deterministic. The SDK may validate elements repeatedly during partial updates and again for final output; Casai adds no redundant parsing or exactly-once guarantee. Keep validators inexpensive and add stateful enrichment, such as random IDs, after validation.
The native SDK result properties retain their types and behavior. In SDK 7, stream is the execution-event stream and fullStream is its deprecated alias. SDK methods select their own operation: writer.stream() returns a streaming result even when its ordinary call is complete.
Final-Answer Streaming in Tool Loops
Native textStream includes text from intermediate tool steps. Casai does not predict finality or filter this stream. For an answer-only stream, make the answer-producing phase explicit: gather research, then invoke a separate streaming writer without tools.
import { isStepCount } from 'ai';
const research = create.LLMAgent.withTemplate({
model,
tools: { lookup },
stopWhen: isStepCount(5),
prompt: 'Gather factual research notes for this question: {{ question }}',
});
const answerWriter = create.LLMAgent.withTemplate.asStream({
model,
prompt: 'Answer {{ question }} using these findings:\n{{ findings }}',
inputSchema: z.object({ question: z.string(), findings: z.string() }),
});
const question = 'How should a household recycle used batteries?';
const notes = await research({ question });
const answer = await answerWriter({ question, findings: notes.output });
for await (const chunk of answer.textStream) {
process.stdout.write(chunk);
}
lookup is an application-provided research tool. The two phases are an explicit workflow choice. Casai never adds a synthesis call, disables tools or changes the stopping condition to force an answer.
Streaming from a Function
A Function streams when execute returns an async iterable, such as an async generator, and its schema is a stream schema:
const countdown = create.Function({
inputSchema: z.object({ from: z.number() }),
schema: textStreamSchema(),
execute: async function* ({ from }) {
for (let n = from; n > 0; n--) yield `${n}... `;
yield 'Liftoff!';
},
});
for await (const text of await countdown({ from: 3 })) {
process.stdout.write(text);
}
console.log(await collectTextStream(await countdown({ from: 3 }))); // 3... 2... 1... Liftoff!
TypeScript requires execute to produce a stream accepted by its schema: textStreamSchema() accepts string chunks and streamSchema(elementSchema) accepts that element schema's input type. The caller receives parsed elements of its output type. One lazy wrapper applies the schema in the existing consumption pass with one reader and no duplicate producer. The callback runs once and needs no mode flag. Forwarding an input stream retains its current consumption state rather than making it fresh again.
To forward a streaming LLMAgent's live text, return result.textStream with schema: textStreamSchema(). This stream includes text from intermediate tool steps. For completed text, await result.output and use schema: z.string() instead; output is a promise in streaming mode whether its specification is omitted or explicit. Neither reading text nor validating a string establishes workflow completion; inspect native events and finish reasons when that matters.
The callback receives one flat context containing schema-produced application values, private configured dependencies, and separately parsed tool-context fields. The _toolOptions property holds execution metadata, including cancellation. .asTool collects a finite returned stream into a completed tool result; it does not send intermediate stream values as SDK preliminary UI results. Use an explicit native SDK tool when that progress protocol is needed.
Streaming a Template
Create a Template with .asStream to receive its text as it renders. Children that should stream into it are also created with .asStream; the same Template source collects or forwards their text:
Work in progress: this example requires the planned Cascada native streaming integration.
const writeIntro = create.LLMAgent.withTemplate.asStream({
model,
prompt: 'Write a two-sentence introduction to {{ topic }}.',
inputSchema: z.object({ topic: z.string() }),
});
const newsletter = create.Template({
template: 'Weekly update\n\n{{ writeIntro({ topic: topic }).textStream }}',
inputSchema: z.object({ topic: z.string() }),
context: { writeIntro },
});
const liveNewsletter = create.Template.asStream({}, newsletter);
const issue = await liveNewsletter({ topic: 'battery recycling' });
for await (const text of issue) {
process.stdout.write(text);
}
The heading arrives at once, and the introduction follows as the model writes it. await newsletter({ topic: 'battery recycling' }) renders the same source into a complete string. See streaming and streaming through templates and scripts.
See the Cascada template reference for expressions, loops, includes, and inheritance.
Streaming Through Templates and Scripts
A child keeps its declared execution mode when a parent streams. A child streams when it was created with .asStream, or is a Script or Function whose schema declares a stream. The newsletter Template collects the streaming writeIntro text during complete rendering or forwards its chunks during streaming:
Work in progress: this example requires the planned Cascada native streaming integration.
const page = await newsletter({ topic: 'battery recycling' });
const live = await liveNewsletter({ topic: 'battery recycling' });
Assignments, property access, function arguments, and filters retain ordinary values when the called component is configured for complete execution:
{% set summary = summarizeText({ text: text }).output %}
{{ summary | truncate(100) }}
Likewise, var summary = summarizeText({ text: text }).output in a Script still obtains the complete string. An explicit streaming child returns its declared stream/result in both parent modes; consume it intentionally before using a complete value in calculations.
A Script exposes live output by returning a tstream channel for text or stream channel for elements, with a matching stream schema. A channel snapshot or ordinary array is a completed value. Native streams preserve their kind and logical order across context and component calls. In a script, iterating or assigning a channel sees the elements emitted before that point in source order, and an assignment takes a snapshot: an array or a string. A JavaScript stream assigned in a script stays a reference. Cascada's default internal sharing lets several loops read its retained sequence; passing the source to JavaScript or returning it does not restore consumed items. Schema adapters may wrap a source while preserving its producer and consumption state.
Independent producers may finish out of order. Cascada delivers output in logical source order: for explicitly streaming {{ slowA() }}{{ fastB() }}, available text from slowA can be displayed immediately while fastB waits behind it. Intermediate calls do not publish output merely because they execute.
Ordered and Unordered Streams
Streams deliver text chunks and complete elements in logical order, even when producers run concurrently. A later result waits for the earlier output position before it is delivered.
Work with images, audio and video
Use the component reference for each provider operation's settings and result fields. These examples explain how to pass media between operations, consume it, and keep ownership of streams and voice sessions clear.
Pass a WAV file or a Web Audio AudioBuffer directly to Transcriber or Translator. Casai reads its format and prepares the samples in the browser or Node.js. For other codecs, ordinary Transcriber can send a recording the provider accepts. To decode compressed audio locally or extract a track from video, use .loadsAudio in Node.js with node-av installed. Audio formats and examples
Images and Files in LLMAgent Messages
For image understanding, pass an image content part to a capable language model:
const vision = create.LLMAgent({ model: visionModel });
const description = await vision([
{
role: 'user',
content: [
{ type: 'text', text: 'Describe the visible damage.' },
{ type: 'image', image: new URL('https://example.com/product.png') },
],
},
]);
console.log(description.output);
Replace the example URL with your own image. File parts and other supported message content also remain structured through Casai preparation. Script/function prompts can return these message arrays directly.
The model and provider determine supported media and formats. Generated files and content parts remain available on LLMAgent results. output controls parsed text or structured values; use ImageGenerator, Transcriber, or SpeechGenerator for their dedicated operations.
ImageGenerator
ImageGenerator generates images from a prompt and supports editing when the model provides it.
const illustrator = create.ImageGenerator({ model: imageModel });
const pictures = await illustrator.run({
prompt: 'A watercolor illustration of a recycling workshop.',
n: 2,
});
console.log(pictures.images);
Configure an image model and reusable defaults. Shorthand accepts text, reference images, mask and count: (text, images?, mask?, n?). Prepared calls put context before media: (source, context, images, mask, n), or (context, images, mask, n) with a configured source. This applies to templates, scripts, functions and loaded sources. Omit identifiable optional slots: (textTemplate, context, images) has no mask; (textTemplate, images) omits satisfied context; (text, n) requests a count without media. Required context still has to be supplied or configured. .run({ prompt, images, mask, n, ...settings }) names these inputs and supports size, aspect ratio and seed. Available counts, sizes and editing options depend on the model.
All input modifiers and .asTool are supported. An inline template can be a string or an SDK image-prompt object: Casai renders the object's text and retains its images and mask. Script/function preparation can produce the complete text prompt or image-prompt object. As a tool, the generated images go to your application and, as image content, to the model; see specialized components as tools.
Configured images can provide a reusable visual style while each call describes a new subject:
const drawInStyle = create.ImageGenerator.asTool({
model: imageModel,
description: 'Draw the requested subject using the reference style.',
images: styleReferences,
inputSchema: z.object({ prompt: z.string() }),
});
const cabin = await drawInStyle({ prompt: 'A mountain cabin at sunset.' });
The tool uses the validated prompt field directly. Changing the text retains the configured reference images and mask, including through .run({ prompt: 'New subject' }). Supplying new images replaces the old ones and drops the previous mask unless the call includes a new mask. An empty image array selects text-only generation and requires prompt text. A complete native prompt object follows the SDK's own rules.
You can also configure images and mask separately from the source. This is useful when prompt holds a function, script or loaded resource rather than a native image-prompt object:
const drawSubject = create.ImageGenerator.withFunction({
model: imageModel,
images: styleReferences,
inputSchema: z.object({ subject: z.string() }),
prompt: ({ subject }) => `A watercolor illustration of ${subject}.`,
});
await drawSubject({ subject: 'a mountain cabin' }); // Uses styleReferences.
await drawSubject({ subject: 'a mountain cabin' }, otherReferences);
The same defaults work with text, template and loaded sources, including prepared tools; they are not published as model arguments. Call-time media override these defaults. Separate media defaults survive source-mode changes through ordinary configuration inheritance: replacing only configured images retains an inherited separate mask. To replace the images and remove that mask, use { images: newReferences, mask: undefined } in child configuration. A mask-only update retains inherited images. Own undefined clears a configuration field, while invocation undefined retains its default. At call time, supplying new images still drops the configured mask unless that call also supplies a defined mask.
A configured native prompt object, including a structured template, supplies its own media bundle instead of borrowing separate configured defaults. Complete explicit prompt objects and complete function/script results likewise select their own media and ignore all configured media defaults. Separate invocation fields can override the selected bundle's images or mask.
An explicit native image-prompt source replaces the whole bundle and follows native source validation. A separate application-context schema does not validate that authored source or a preparer result. When an object is supplied inside a public model/tool prompt argument, that argument schema must permit it; a string-only tool argument rejects it. .run({ prompt: { images: [newPhoto], text: 'New instructions' } }) selects those images and removes any configured mask. To remove references, use .run({ prompt: 'New subject', images: [] }); that field-override form sends text-only generation. An explicit native { images: [], text } keeps native edit semantics and is not a clearing shortcut. Separate invocation images and mask override the corresponding fields of any complete prompt object, including function/script results. Replacing images drops the old mask unless the call supplies a defined mask; replacing only the mask keeps the images. For example, image.run({ mask: newMask }) changes only the mask, and image.run({ images: [newPhoto] }) replaces the images and drops the old mask. Text-only source updates retain configured media. Native bytes and input arrays are preserved without mutation.
The result includes generated images with their media data, warnings, and metadata. To understand an existing image with a language model, use LLMAgent image messages. See SDK image generation for editing formats and provider options.
An image exposes .uint8Array, .base64, and .mediaType. For editing, supply the source bytes in a prompt object:
import { readFile } from 'node:fs/promises';
const edited = await illustrator.run({
prompt: {
images: [await readFile('./workshop.png')],
text: 'Change the wall color to light blue.',
},
});
console.log(edited.images[0]?.mediaType);
This requires an editing-capable model. Serve image bytes with their reported media type, or construct a data URL from .mediaType and .base64.
Use the same native shape for an editing template:
const repaint = create.ImageGenerator.withTemplate({
model: imageModel,
inputSchema: z.object({ color: z.string() }),
prompt: {
images: [await readFile('./workshop.png')],
text: 'Change the wall color to {{ color }}.',
},
});
const blueWorkshop = await repaint({ color: 'light blue' });
Transcriber
Transcriber returns a completed transcript. Without inputAudioFormat, it uses the provider's encoded-file operation; OpenAI handles that through its file-transcription endpoint. With inputAudioFormat, it accepts raw audio, uses native streaming and waits for the authoritative final transcript. Transcriber.asStream exposes the live result instead. An unsupported selected operation reports the native error without trying another operation.
import { readFile } from 'node:fs/promises';
const transcriber = create.Transcriber({ model: transcriptionModel });
const recordedAudio = await readFile('./recording.wav');
const transcript = await transcriber(recordedAudio);
console.log(transcript.text);
console.log(transcript.segments);
Use this ordinary call when the provider already accepts the recording. In Node.js, readFile supplies the bytes. In a browser, pass the selected File directly. Both use the AI SDK file operation without node-av. To have FFmpeg open a recording, select a track or convert its format, use .loadsAudio on the server. Audio with and without node-av
recordedAudio contains encoded audio bytes (Uint8Array, Buffer or ArrayBuffer) or base64 data. A native URL instead uses the SDK downloader, including its address checks and byte limit. The installed SDK default is 2 GiB; for model-selected URLs, always set an application-appropriate limit with download: createDownload({ maxBytes }). Strings remain encoded data. Outside .loadsAudio, a native URL cannot be combined with inputAudioFormat: URLs use encoded-file execution, while that format selects supplied raw audio. The download setting is available only on the encoded-file path. Use .loadsAudio for FFmpeg preparation of paths/URLs. The selected provider determines supported formats. The result retains text, segments, language information, and other available SDK fields.
Use .withScript, .withFunction, or .loadsScript to obtain audio before transcription, and .asTool to expose the completed operation. Text/template modifiers do not apply to audio payloads. See SDK transcription.
Use .loadsAudio.asTool for a recording selected by your application. Configure its trusted source and the target accepted by the model:
const transcribeRecording = create.Transcriber.loadsAudio.asTool({
model: transcriptionModel,
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
audio: authorizedRecordingUrl,
description: 'Transcribe the configured audio recording.',
inputSchema: z.object({}),
});
Install the desired node-av build; no loader setting is required. This example uses a streaming-capable model accepting 24 kHz mono PCM16 and returns a completed transcript. The model invokes the tool with no resource argument. Trusted application calls can override the recording with a path, URL, encoded bytes or a byte stream: transcribeRecording(uploadedStream) and transcribeRecording.run({ audio: uploadedStream }) both select the supplied stream. Your application authorizes the configured resource, including redirects and playlist children. To let a model select a recording for native preparation, expose a Function/Script workflow that resolves an authorized recording ID and calls an ordinary .loadsAudio component through .run({ audio, mediaSettings }). Source credentials and native options stay in trusted settings. See media loading.
For a tool that accepts a public recording URL from the model, pass a validated URL to ordinary Transcriber. The SDK checks the target, redirects and resolved addresses. Configure the download size limit on the component.
import { createDownload } from 'ai';
const transcribePublicUrl = create.Transcriber.asTool({
model: transcriptionModel,
description: 'Transcribe an audio recording at a public URL.',
inputSchema: z.object({ audio: z.url().transform(value => new URL(value)) }),
download: createDownload({ maxBytes: 20 * 1024 * 1024 }),
});
The model supplies { audio: "https://example.com/recording" }. The SDK downloads it once, forwards cancellation and uses the response media type when available. When FFmpeg opens a URL through .loadsAudio, the application authorizes that resource and its redirects and children separately.
Streaming transcription
Transcriber.asStream produces transcript events while receiving live audio. It requires a streaming-capable transcription model and audio in the declared format. It uses the AI SDK's experimental experimental_streamTranscribe API.
Finite raw bytes are also accepted, but completion follows the provider's streaming session rules. The current OpenAI adapter commits once after input ends and finishes on the first transcription-completed event. This does not establish support for arbitrary long recordings or multiple completed items; use ordinary Transcriber for whole files.
const transcriberStream = create.Transcriber.asStream({
model: streamingTranscriptionModel,
});
// audioStream is a ReadableStream<Uint8Array | string> of raw audio chunks.
const transcriptStream = await transcriberStream(
audioStream,
{ type: 'audio/pcm', rate: 24000 },
);
for await (const part of transcriptStream.fullStream) {
console.log(part);
}
console.log(await transcriptStream.text);
For live captions, read fullStream first so your application sees each event. After the loop, await text for the transcript to pass to the next step. A workflow that only needs the final transcript can await text directly. To show captions in a Template or Script, select the text from the events you consume. Streaming transcription return fields and errors
Use (audio, inputAudioFormat) or .run({ audio, inputAudioFormat }). Configure inputAudioFormat to shorten this to transcriberStream(audioStream); both entry paths require an unconfigured format. Ordinary Transcriber tools using raw audio require a configured format because their model-facing arguments are input/preparation data; Transcriber.asStream has no tool form.
A request-specific component can configure its one-shot audio and be called without arguments:
const transcribeThisRequest = create.Transcriber.asStream({
model: streamingTranscriptionModel,
audio: requestAudio,
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
});
const transcript = await transcribeThisRequest();
console.log(await transcript.text);
The same rule applies to configured Translator audio and native-streaming SpeechGenerator text inputs. Inheritance shares the input object; it does not create a new stream. Once Casai hands a ReadableStream to the SDK, handing that exact object off again throws ValidationError, even through a different component. A failed SDK attempt still claims the input; failures before dispatch do not. Reusable finite audio bytes are wrapped in a fresh stream for each call. Casai does not promise detection of external consumption or generic iterator reuse.
For repeatable operations, a configured function/script preparer can open a fresh stream each time. Normal native LLMAgent results also provide independent textStream projections from the same execution: a preparer can obtain a new view per invocation. Capturing one view in configuration does not make that view reusable. Explicit makeSharedIterable sharing retains history; its owner controls disposal. Audio still needs a new toReadableStream(sharedAudio) bridge per call, while streaming speech can accept a replayable iterable directly. Casai does not enable replay automatically for live input.
On prepared components, one object is application context. To supply an audio format when context is optional, use transcribe({}, format), transcribe(undefined, undefined, format), or .run({ inputAudioFormat: format }). The format object cannot occupy the context slot.
Script/function modifiers can obtain raw audio; supply its format after context or through .run(). Use ordinary Transcriber.withFunction.asTool for named preparation arguments and a completed transcript:
const transcribeRecording = create.Transcriber.withFunction.asTool({
model: streamingTranscriptionModel,
description: 'Transcribe a stored recording.',
inputSchema: z.object({ recordingId: z.string() }),
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
audio: async ({ recordingId, _toolOptions: { abortSignal } }) =>
openRecordingAsPcmStream(recordingId, { signal: abortSignal }),
});
Here openRecordingAsPcmStream is an application helper that opens a fresh, finite raw PCM stream in the configured format for each execution. A preparer may also provide an explicit normal completion boundary. The tool selects text, segments, language and durationInSeconds from that execution's native final-result promises; the model receives transcript text by default. The SDK consumes the stream, and native promise rejection or success is preserved. Casai does not concatenate events, add another reader or share an already-consumed source between calls. An indefinitely open source is not a valid tool input. Direct calls on this ordinary tool component also return the completed transcript result. See SDK streaming transcription.
SpeechGenerator
SpeechGenerator converts text into completed spoken audio. String text with an omitted or string outputFormat selects native complete generation. An object outputFormat or native non-string text input selects native streaming, which the ordinary component collects. These are request-shape rules: Casai does not test model capabilities by trying one operation and falling back to another.
For a streaming-only speech model and string text, configure a supported format object once. For example, if that model accepts 24 kHz PCM:
const completeSpeech = create.SpeechGenerator({
model: streamingSpeechModel,
outputFormat: { type: 'audio/pcm', rate: 24000 },
});
const spokenRecording = await completeSpeech('Welcome home.');
console.log(spokenRecording.audioFormat);
A string-text call without the object format selects complete execution and may fail on a streaming-only model. Native streaming speech itself permits an omitted format; the object here makes the ordinary call's operation unambiguous. Non-string text plus a complete-only string format is incompatible; the ordinary component rejects it before sending a request. Use .asStream to receive incremental output.
const speaker = create.SpeechGenerator({ model: speechModel });
const spoken = await speaker('Your replacement is on its way.');
console.log(spoken.audio);
Configure a speech model and reusable defaults. Shorthand takes (text, voice?), such as speaker('Welcome home.', 'alloy'). Format and narration controls use .run({ text, voice, outputFormat, instructions, speed, language }); for example, .run({ text: 'Welcome home.', outputFormat: 'wav', instructions: 'Speak warmly.', speed: 0.9 }). All input modifiers prepare the text to speak; .asTool is also supported. Tools retain the actual audio for your application and use native media content for a supporting receiving adapter/model. The default forwards native file data and media information, including audio/pcm when returned. Complete raw speech may expose no sample rate; Casai does not invent one or a WAV header. Format acceptance belongs to the SDK adapter/provider. toModelOutput is optional. Use it with application-known sample semantics when you want to package raw audio differently. Casai does not guess missing format details or automatically wrap samples in WAV.
The result retains generated audio, format information, and metadata. Combine Transcriber, LLMAgent, and SpeechGenerator for a recording-to-answer workflow. See SDK speech generation.
spoken.audio exposes .uint8Array, .base64, and .mediaType. To return playable audio from a server handler:
const audioResponse = new Response(Uint8Array.from(spoken.audio.uint8Array), {
headers: { 'Content-Type': spoken.audio.mediaType },
});
When saving to a file, choose an extension matching the actual media type or configure a supported output format explicitly.
Streaming speech
SpeechGenerator.asStream speaks a complete string or a native stream of text deltas/parts. Use a streaming-capable speech model; the SDK reports unsupported models. The current OpenAI speech adapter generates complete audio, while the SDK's streaming speech example uses ElevenLabs.
const answerer = create.LLMAgent.asStream({ model });
const say = create.SpeechGenerator.asStream({
model: streamingSpeechModel,
});
const reply = await answerer('Describe a peaceful mountain scene.');
const spoken = await say(reply.textStream);
for await (const part of spoken.fullStream) {
if (part.type === 'audio') {
await sendAudio(part.audio, part.audioFormat); // Your application's transport.
}
}
console.log(await spoken.usage);
Shorthand is (textOrTextStream, voice?); .run() accepts the native fields by name. Text can also be an iterable/array of strings or native text parts with per-part voice/provider options. Templates and text loaders produce a complete string; script/function preparation can return any native text input. Incoming text chunks stay data and are not templated. Whether synthesis begins before text ends depends on the provider. A configured stream/iterator can bind a single-use component; strings, arrays and genuinely replayable iterables can be reused. For repeated consumption, pass a fresh stream or obtain a new branch in a preparer.
Select either audioStream for bytes or fullStream for audio format, raw and error parts, before accessing final metadata promises. These are alternative single-consumer views. Chunks need not be standalone audio files. Native error events, callback behavior, cancellation and finish/failure behavior are preserved; audioStream skips error parts, while fullStream exposes them. The native streaming operation takes an audio-format object; native complete speech generation takes a string format. With .asStream, the component returns the live SDK result and cannot be a tool. Ordinary SpeechGenerator collects this native operation when the request uses an object format or non-string text, including through .asTool.
Translator
Translator translates raw speech into target-language audio and text through one native streaming translation operation. Ordinary calls collect its completed result; Translator.asStream exposes live events. A supporting provider model is required; OpenAI exposes translation('gpt-realtime-translate').
Pass an uncompressed WAV, a Web Audio AudioBuffer or raw samples to Translator. Configure the model's target format and language once. For compressed recordings or video, Translator.loadsAudio on Node.js detects the source and prepares the audio. Audio formats and examples
const translateRecording = create.Translator({
model: translationModel,
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
targetLanguage: 'fr',
});
const completed = await translateRecording(recordingPcm);
console.log(completed.translationText, completed.audio);
To consume incremental events instead:
const translate = create.Translator.asStream({
model: translationModel,
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
targetLanguage: 'fr',
});
const translated = await translate(audioStream);
for await (const part of translated.fullStream) {
console.log(part.type); // Audio and source/translated text events.
}
console.log(await translated.translationText);
Shorthand takes (audio, inputAudioFormat?, targetLanguage?). Configure either secondary input or supply it at invocation; translate(audioStream, 'es') can omit a configured format. With .loadsAudio, a leading string is always the file/URL resource. When the resource is configured, use translate(undefined, undefined, 'es') or .run({ targetLanguage: 'es' }). .run() names the same fields and native options, including source language and output format. Script/function preparers can open raw audio; text/template modifiers do not apply to it. Required context remains explicit where its object shape overlaps an audio-format object.
Consume the single fullStream before final text/metadata promises when both are needed. Audio parts keep their native bytes-or-base64 form; final source/translation text comes from the SDK's finish data. An audio-only provider may return empty translation text. The streaming result has no separate audioStream alias. Ordinary Translator and its .asTool form collect the same native operation; .asStream cannot combine with .asTool. Provider language/format validation, errors and cancellation retain native behavior.
Audio with and without node-av
Configure the model's target once. For example, inputAudioFormat: { type: 'audio/pcm', rate: 24000 } requests 24 kHz mono, signed 16-bit little-endian PCM for the model. It applies to transcription with a raw-input model and to translation. For ordinary file transcription, omit it and Casai sends the provider an encoded recording.
What to pass for each audio source
| Your input | Source format information you supply | How Casai handles it |
|---|---|---|
Uncompressed WAV as a File, Blob, Uint8Array or ArrayBuffer |
None. The WAV header contains encoding, sample rate and channel count. | For raw model input, Casai reads the header, mixes channels to mono and resamples to the target. For file transcription it passes the WAV through. |
Web Audio AudioBuffer |
None. The buffer exposes its rate, channels and floating-point samples. | Pass the whole buffer directly. Casai reads its channels and prepares a WAV or the model's raw PCM. |
Headerless Int16Array, Int32Array, Float32Array or Float64Array |
Set sourceFormat.sampleRate in Hz and sourceFormat.channels. The array type supplies the encoding. |
Casai reads interleaved samples. For file transcription it wraps them in WAV. For raw model input it converts them to the target. |
Headerless bytes or a raw chunk stream that already matches inputAudioFormat |
None beyond the configured model target. | An ordinary component forwards the samples as supplied. |
| Headerless bytes or a raw chunk stream that needs conversion | Set sourceFormat with sampleRate, channels and encoding. A byte buffer or base64 chunk carries none of those fields. |
Casai converts integer or floating-point PCM. A raw stream is processed as chunks arrive. |
| Another encoded recording, such as WebM/Opus, MP3, or video | None for normal files. | For file transcription, send a recording the provider accepts directly. For decoding, track extraction or conversion, .loadsAudio in Node.js lets FFmpeg inspect the container and its audio tracks. |
For example, a browser file picker can hand its WAV File straight to a translation component. The recording can be stereo or sampled at a different rate.
const translate = create.Translator({
model: translationModel,
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
targetLanguage: 'fr',
});
const { translationText } = await translate(wavFile);
If recording is a decoded Web Audio AudioBuffer, await translate(recording) includes all its channels. Some capture or editing workflows take just one channel, for example the microphone on channel 0 of a stereo interview. getChannelData(0) returns that channel as a Float32Array. The array contains the sample values. The rate stays on the original AudioBuffer, and selecting a single channel gives channels: 1. Web Audio specification
const result = await translate.run({
audio: recording.getChannelData(0),
sourceFormat: { sampleRate: recording.sampleRate, channels: 1 },
});
Live microphone capture is another common source of headerless PCM. An AudioWorklet receives samples per channel. If the capture code sends just the samples to a server, send the capture rate and channel count once alongside them. Sending the underlying bytes also drops the typed array's encoding. Uploading a complete WAV preserves all three fields in its header. Web Audio worklets
Choose WAV file, Web Audio AudioBuffer or Headerless PCM under Recording example in either component's matrix. All three examples use the same model target. WAV file · Whole AudioBuffer · First-channel PCM
Direct WAV conversion supports little-endian RIFF/WAVE containing integer PCM or IEEE floating-point audio. Use .loadsAudio for compressed WAV, WebM/Opus or other containers that need decoding. For a model that accepts a different raw encoding, such as G.711, supply chunks already in that encoding.
For byte input, Casai accepts pcm_u8, pcm_s16le, pcm_s24le, pcm_s32le, pcm_f32le and pcm_f64le. The browser and Node.js use workers for PCM conversion. In a browser, allow blob: workers in the Content Security Policy. The verified browser pairing uses cascada-engine version 0.7.0. Casai's published dependency range still requires a coordinated update.
A direct ReadableStream supplies raw model chunks, optionally with sourceFormat for conversion. For a WAV, pass the File or Blob itself. If a finite encoded recording arrives only as a stream in the browser, await new Response(stream).blob() gives Casai the whole recording with its header. On Node.js, .loadsAudio accepts an encoded byte stream directly. Keep supplied samples unchanged until consumption finishes and supply a fresh stream for each call.
Open and convert recordings with node-av
Install the LGPL build in the Node.js application that will open the media. The npm alias gives the binding the name Casai resolves. Casai calls FFmpeg through that binding, so a separate command-line installation is unnecessary.
npm install node-av@npm:node-av-lgpl@7.1.0
Pass the original recording to Transcriber.loadsAudio or Translator.loadsAudio. FFmpeg detects the input container, codec, rate and channels and selects the best audio track. Usually the only format setting is the target your model accepts. For a raw-input model use inputAudioFormat. For file transcription use fileAudioTarget with the accepted container and codec. Add a target rate or channel count only when the model requires it.
For example, POST a browser's original MediaRecorder recording or a video file to your server. This transcription model takes a 16 kHz mono PCM16 WAV.
const transcribeUpload = create.Transcriber.loadsAudio({
model: transcriptionModel,
fileAudioTarget: { format: 'wav', codec: 'pcm_s16le', rate: 16000, channels: 1 },
});
if (!request.body) throw new Error('The request needs a recording.');
const { text } = await transcribeUpload(request.body);
The request body is forward-only. For a container that needs seeking, pass a file path such as './interview.mp4' or complete encoded bytes. Casai copies compatible encoded audio when possible, converts when needed and owns cleanup. To select a different audio track, set mediaSettings.track to its zero-based stream index. FFmpeg also needs an input description for headerless PCM when its rate already matches the model. Supply sourceFormat with rate and channels for a numeric sample array, or include the encoding for raw bytes, streams or paths. An ordinary component can forward already-compatible raw bytes with only inputAudioFormat. Keep mediaSettings.format for an explicit native demuxer override.
.loadsAudio loads the optional binding on invocation and requires Node.js with node-av installed. .asStream selects incremental results for either direct or native input. Ordinary SpeechGenerator and Translator calls return completed audio bytes. Completed audio
Loading media and format auto-detection
Use .withAudio to return an inherited audio component to ordinary supplied-audio behavior. Clear inherited mediaSettings and any file-preparation target when leaving .loadsAudio. Source selection does not clear inherited .asStream or .asTool; an unmodified child preserves both source and delivery choices. Finite supplied bytes can be reused, while a supplied stream is single-use. Upload the File or Blob itself when sending a browser recording to a server. Supplied bytes/streams do not carry their former filename, URL base, seeking capability or authorization for external playlist resources. Native byte preparation therefore defaults mediaSettings.options.protocol_whitelist to '', denying referenced local files and network resources while allowing the supplied bytes themselves. Ordinary self-contained recordings still work. A trusted explicit protocol whitelist can permit intentionally authorized child resources; null/undefined retain the default. Paths and URLs keep their native protocol handling.
Casai tracks each stream handed to a component or to native preparation. Handing the same ReadableStream to Casai again raises ValidationError before another native read or provider request. A failure after handoff still claims that stream; validation, missing-installation and cancellation failures before handoff do not. Supply a fresh stream for another attempt. This identity check does not detect external consumption or every reused iterator, and never buffers or replays the input.
Use Transcriber.loadsAudio or Translator.loadsAudio for a file path, media URL, encoded Uint8Array/ArrayBuffer or ReadableStream<Uint8Array>. FFmpeg/node-av handles acquisition internally; no loader or public backend binding is configured. A relative path therefore resolves against the process working directory, not a loader root. Every .loadsAudio call requires node-av, including a simple WAV recording; it has no JavaScript file/fetch fallback. A missing native installation is reported when preparation is requested. Construction does not open media. Source settings live in mediaSettings: track selects an absolute container stream index, format optionally forces an input demuxer, and options is an open dictionary of native FFmpeg input options and native-compatible scalar values. Option availability and handling belong to the installed backend. Omit format for normal recordings.
FFmpeg probes the content. A path or URL can also provide a filename or response Content-Type. Casai currently passes an uploaded File or Blob to FFmpeg as bytes, so detection uses its contents. An extensionless recording can work. Stream inspection may read packets or decode frames from other tracks, including video, to discover their metadata. Only the selected audio goes into the prepared output. Compatibility depends on the installed build's demuxers/codecs and the input's ability to seek. A supplied byte stream retains its read-ahead for the same execution and remains forward-only.
Set mediaSettings.format only to override native input detection. For example, FFmpeg can open an MP4 container, select its AAC track and convert it to the model's PCM target. Headerless PCM needs a source description because a .pcm filename carries no rate, channel count or encoding. For an uncompressed WAV, an ordinary component can read the header and convert the samples directly.
Configure inputAudioFormat for the raw format the model accepts. Casai prepares an audio/pcm target as mono, signed 16-bit little-endian samples at the requested rate. For a 24 kHz target and a 48 kHz stereo recording, it mixes the selected track's channels and resamples to 24 kHz.
File transcription preserves the selected audio's quality within the provider's accepted formats and limits. It keeps a compatible encoding and sample properties, using native track extraction or remuxing where possible. Casai checks the primary target and then its alternatives in declaration order for a compatible copy. If none matches, it converts to the primary target, preserving sample properties within that target's constraints and native encoder support. Choose a lossless primary target when you want to avoid another lossy encoding pass; alternatives are used only for copying. It does not force every recording to PCM16 WAV or 24 kHz mono. Larger files increase memory and upload time without restoring information absent from the source. Native model information does not currently establish accepted file targets, so .loadsAudio file transcription requires a target describing accepted formats and limits in the finished component's trusted configuration, including inheritance. One known compatible target is sufficient; a set of accepted alternatives permits preserving more source encodings without copying a complete provider catalog. Named calls can override that target. Raw transcription instead accepts inputAudioFormat from configuration or the call. The file target is separate from source mediaSettings and cannot be combined with inputAudioFormat, which selects raw streaming instead. Output must also be correctly handled by the SDK's file-input path. An output that cannot fit its configured bounds fails rather than silently losing speech, being split into extra model calls or triggering a trial-upload/re-encoding loop.
Copy/remux compatibility and reported file-format metadata come from native inspection. A later format change inside a playlist may not be reflected in that metadata. Duration limits include encoder padding and accept recordings exactly at the limit. For file transcription, choose a container the SDK identifies correctly. For example, FFmpeg can produce AIFF, but the SDK's byte detector would label it as WAV. .loadsAudio rejects an unidentified non-WAV file before contacting the provider.
Opening and stream inspection may read packets, seek or wait for network data before prepared audio is available. A supplied byte stream uses FFmpeg's default probe size. An explicit mediaSettings.format bypasses format detection and still allows stream-info inspection. Use invocation cancellation and applicable native probe or network options. Failed detection or an unsuitable override reports an error.
.loadsAudio uses one media-preparation path to open the resource, select the native best audio track or explicit index, and prepare that audio for the model. It does not hand the resource to a second SDK downloader. Ordinary Transcriber separately accepts supplied encoded/raw audio or a native URL through the SDK download hook. Use an explicit preparer for application-owned downloads or fresh streams. FFmpeg can feed the raw-audio SDK stream while reading the resource, after required probing; the encoded-file SDK operation needs complete prepared bytes. Provider limits and first-result timing still apply. Completed audio results retain their output audio in memory.
The native media path does not inherit the SDK downloader's URL protections or byte limits. Applications exposing media tools must authorize the resources models can select, including local files, redirects and playlist children. A closed input schema alone does not establish that authority. Server-resolved recording identifiers and application-controlled preparation are useful where arbitrary resource access is inappropriate.
A .loadsAudio.asTool component requires configured audio, possibly inherited. SDK tool execution and injected tool calls use that source; model arguments cannot replace it. Declared context fields may still serve callbacks, but even a field named audio is application data rather than a resource override. Use a closed empty schema when no public data is needed. Ordinary application calls and .run({ audio, ... }) retain explicit trusted source overrides. Dynamic model-selected native resources belong in an explicit Function/Script workflow that resolves and authorizes the recording before invoking .loadsAudio.run(). Ordinary Transcriber tools still accept native SDK URL input with downloader protections. FFmpeg protocol options do not provide a general destination/redirect/playlist authorization mechanism.
.loadsAudio owns resources it opens until the SDK accepts them. Preparation, cancellation or an early dispatch failure closes those resources. After handoff, consume or cancel the native stream result under its existing ownership rules.
A Function or Script workflow can resolve a recording ID and call a configured .loadsAudio component through .run({ audio, mediaSettings }) with fresh private credentials or a track choice. The component owns preparation and cleanup.
Keep source headers in mediaSettings.options.headers; model headers authenticate the model request separately. A supplied mediaSettings object in .run() replaces the whole configured group. Include settings you want to retain when supplying fresh credentials; {} restores media defaults, while an omitted group retains configuration.
Choosing and distributing a native build
The LGPL build includes FFmpeg's own AAC encoder, audio decoding and resampling. It omits GPL components and libfdk_aac. Applications choosing the GPL build can install node-av@7.1.0 under the same dependency name. The same Casai calls work with either build. The separate @seydx/node-av-ffmpeg-lgpl package supplies command-line tools. Upstream variants and alias installation
Check the selected binary's OS/CPU and libc requirements, codec set, footprint and license notices. JavaScript imports do not reduce the codecs in that binary. The JavaScript wrapper uses MIT and the native artifacts have their own licenses. If you redistribute LGPL-covered code in an application, addon, installer or container image, check the exact license version for notices, corresponding source and build materials, and the ability to replace or relink the library with modifications. This applies to static FFmpeg code inside a dynamically loaded Node addon. LGPL 2.1 · LGPL 3
GPL permits commercial use and has its own distribution requirements. Assess the application, linking and distribution arrangement for the build you ship. Casai supports the LGPL and GPL builds. Audio extraction from a video does not require the x264 H.264 encoder. Codec patents are a separate consideration. FFmpeg license details · x264 licensing
Completed audio and tools
Use an ordinary speech or translation call when the next step needs complete audio, such as saving a recording. For playback, use the format the provider actually emitted. Collected streaming speech includes that format. For translation, package raw PCM as WAV only when you know the sample layout. Use .asStream when you want to play chunks or inspect events as they arrive. Speech return · Translation return
When an agent invokes Translator.asTool, the application receives the audio and the calling model receives translated text by default. That keeps the full recording out of the model’s text history. An audio-only translation can have empty text. If the next model needs to hear it, use toModelOutput to send a supported audio format on a route that accepts it. For a recording chosen by your application, configure it on .loadsAudio.asTool. Translation tool return · Media tool compatibility
Browser voice sessions
Use the AI SDK’s experimental realtime client in the browser and VoiceAgentBackend on your server. For a token-based session in React, pass a browser-compatible realtime model and api: { token: '/api/voice/setup' } to experimental_useRealtime from @ai-sdk/react. Call connect() when the user starts the conversation and close() when it ends. For a model that supports Live WebRTC, point api.session at your server’s WebRTC route instead. AI SDK browser example
VoiceAgentBackend
Your server authenticates the user, authorizes session creation and tool calls, and keeps provider keys and tool executors private. In a token-based session, it returns a short-lived credential that lets the browser connect to the provider. The browser owns the live connection, microphone and playback.
The AI SDK’s experimental realtime models offer different setup paths. The examples below show the server’s part in turn-based token setup, Live WebRTC negotiation and a server relay. VoiceAgentBackend token return
In token-based turn-based sessions, the browser runs capture/playback, text input and supported interruption controls, and receives tool calls. The server creates a short-lived token with initial instructions/voice and runs tools that need server-side data or secrets. This setup form is:
const support = create.VoiceAgentBackend.withTemplate({
model: realtimeModel,
instructions: 'You are the support agent for {{ company }}. Keep answers short.',
inputSchema: z.object({ company: z.string() }),
voice: 'alloy',
tools: { lookupOrder },
toolsContext: { lookupOrder: { accountId: authenticatedAccount.id } },
});
// In the token route: accept only this application's browser preferences.
const pcm24k = z.strictObject({
type: z.literal('audio/pcm'),
rate: z.literal(24000),
});
const browserRequest = z.object({
sessionConfig: z.object({
voice: z.enum(['alloy', 'verse']).optional(),
inputAudioFormat: pcm24k.optional(),
outputAudioFormat: pcm24k.optional(),
}).optional(),
}).parse(await request.json());
const setup = await support.run({
...browserRequest.sessionConfig, // Parsed allowlist; server policy is excluded.
context: { company: 'Acme' },
});
// Respond with setup: { token, url, expiresAt, tools }.
// In the route the browser calls from its onToolCall handler:
const output = await support.executeTool(
{ toolCallId, toolName, args },
{
abortSignal: request.signal,
},
);
const toolResponse = Response.json(output === undefined ? null : output);
// Return toolResponse; the browser's onToolCall returns await response.json().
The SDK browser sends { sessionConfig } to the token route. Select the preferences your application permits; the example accepts two voices and 24 kHz PCM. Other browser fields are not forwarded. Trusted server .run() calls can set native voice, modalities, audio formats/transcription, turn detection and provider options, along with token expiration. Instructions and registered tool definitions come from server configuration/preparation. Providers that require session config when creating the token receive the full prepared config.
The ordinary call prepares instructions and returns SDK session setup; .run() is its named form. The component holds no mutable session state. The browser owns the live connection. executeTool(call, executionOptions) selects an available registered tool, validates its arguments/context through the same runner as other Casai tool calls, and executes once, forwarding the supplied call ID and cancellation. Unknown or unavailable tools are rejected. Model arguments remain separate from server-supplied trusted context.
executeTool() is a direct executor, like a native tool's execute(): it does not evaluate needsApproval or run the LLMAgent approval loop. The application must authorize the call and obtain any required user approval before invoking it.
This method returns the tool's execution result. The realtime browser sends that result as native function-output JSON; it does not apply the language-generation tool's toModelOutput formatter. Returning encoded audio or images therefore sends tool data rather than playing audio or creating a rich media tool message. Use the native session's speech response or application playback for audio delivery.
Convert a completed undefined result to JSON null at the HTTP boundary, as above. Native onToolCall treats an undefined return as no automatic submission, so returning it directly leaves the call pending. Response.json(undefined) also fails. The helper preserves the original execution result; this conversion belongs to the application's transport response.
A rejected onToolCall callback only notifies native onError; it does not submit a function output. The browser relay must therefore choose how to settle HTTP, validation and transport failures. For an application that wants the conversation to continue with a bounded failure message:
import type { Experimental_RealtimeSessionOptions } from 'ai';
const onToolCall: NonNullable<Experimental_RealtimeSessionOptions['onToolCall']> =
async ({ toolCall }) => {
try {
const response = await fetch('/api/voice/tool', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(toolCall),
});
if (!response.ok) return { error: 'The tool result could not be obtained.' };
return await response.json();
} catch {
return { error: 'The tool result could not be obtained.' };
}
};
Supply this callback to the native browser session. The returned error object is application data sent through the native function-output protocol, rather than a Casai error envelope. It does not disclose server error details, assert that the action had no effects or retry it. An application may instead deliberately keep the call pending for later submission or close the session; an error notification alone does not settle it. Server .executeTool() keeps its normal throwing behavior.
Use authenticated application endpoints exposing only the account's allowed tool registry; the SDK recommends application-specific tool endpoints. Each route constructs or recovers the matching server-owned configuration and context, including public defaults selected during setup. The example's authenticatedAccount comes from server authentication, and request is the execution HTTP request. The browser relays the native call and returns its response to the SDK. .executeTool() reuses Casai's validation/dispatch within that boundary; the application still owns transport and authorization.
The helper exposes no global HTTP router and grants no operation permission. Prepared instructions are initial guidance; clients can update session guidance under the native protocol. The native token response carries tool definitions, rather than an authoritative replacement for all browser session configuration.
For Live, use the SDK's WebRTC SDP setup or server WebSocket relay capability. Live client delegations appear in session metadata/events and do not invoke onToolCall or use addToolOutput. The application selects its intended component/tool and sends context/results through native sendEvent({ type: 'context-append', ... }). Keep provider credentials and allowed native event/delegation policy on the server. Native experimental setup methods such as doCreateWebRTCSession are published SDK interfaces; they are usable while experimental.
With no tool definitions, prepared session configuration omits the tools property entirely. OpenAI Live rejects that property even when undefined; configuring function tools on Live preserves the native setup/startup error. Use its native delegation protocol rather than advertising turn-based function tools. The documented executeTool route serves turn-based sessions; Live applications call selected components directly and send native context/delegation events. The helper does not add Live function-tool support.
One VoiceAgentBackend accepts a native realtime model instance. Ordinary calls and .run() perform token setup; createWebRTCSession performs native SDP setup and returns { sdp, sessionId }. prepareSessionConfig supplies prepared configuration for relay/browser startup, and executeTool runs allowed server tools. Use the existing model directly for server WebSocket connection information. Unsupported capabilities report their native limitation; the component does not silently choose another transport.
const liveSupport = create.VoiceAgentBackend.withTemplate({
model: liveModel,
instructions: 'Help customers of {{ company }}. Keep answers concise.',
inputSchema: z.object({ company: z.string() }),
providerOptions: { openai: { delegation: { type: 'client' } } },
});
const answer = await liveSupport.createWebRTCSession({
sdp: offerSdp,
context: { company: 'Acme' },
abortSignal: request.signal,
});
// Return the native answer to the SDK browser's api.session endpoint.
liveModel is a provider model with the native Live WebRTC capability. The server selects its allowed native delegation/event policy; do not replace it with policy submitted by the browser. For an application-owned WebSocket relay, obtain native connection information and prepared session configuration separately:
const connection = await liveModel.getServerWebSocketConfig!();
const sessionConfig = await liveSupport.prepareSessionConfig({
context: { company: 'Acme' },
});
// Use connection only on the server; its headers can contain provider credentials.
// Use sessionConfig with the SDK's native startup serialization in your relay.
The component prepares configuration and setup responses; the native model supplies relay connection information. Neither opens a connection or captures audio. The browser continues to use the SDK's experimental realtime interface.
Text and template modifiers prepare the instructions; script and function modifiers return them. VoiceAgentBackend has no .asTool. See SDK realtime for the browser session and provider support.
VoiceAgentClient (planned)
Work in progress. The example below previews the planned
VoiceAgentClientexport fromcasai/client.
Each call will create an independent, disconnected session. A UI will be able to observe that session with getSnapshot() and subscribe() while browser Cascada scripts use the same handle.
import { VoiceAgentClient } from 'casai/client';
const support = VoiceAgentClient({
model: browserModel,
api: { token: '/api/voice/setup' },
sessionConfig: { voice: 'alloy' },
});
const session = await support(); // or support.run()
const unsubscribe = session.subscribe(() => render(session.getSnapshot()));
render(session.getSnapshot());
// From a UI action, subject to browser permissions:
await session.connect();
// connect() may return before readiness; observe connected status before sending.
// In the UI's teardown handler:
try {
await session.close();
} finally {
unsubscribe();
session.dispose();
}
The planned wrapper will use the same token, WebRTC and relay routes as the native client. To share a default voice, define a public object such as { voice: 'alloy' } satisfies Pick<Experimental_RealtimeSessionConfig, 'voice'> and pass it as the browser’s sessionConfig. Keep credentials, instructions and tool executors on the server.
A browser Cascada script will be able to return the handle for later scripts. Once the native status is connected, a script can call session!.sendEvent(command) and inspect the result with is error. The host owns cleanup, including when a script or graceful close fails. Planned VoiceAgentClient controls and state
Video generation (planned)
Work in progress: VideoGenerator is documented before its implementation. The example is syntax-checked but excluded from implemented API type checks.
VideoGenerator produces video clips from text or a native { image, text? } prompt. It follows the common configuration, preparation, ordinary-call and .run() conventions and can be called directly from Cascada Script:
const makeVideo = create.VideoGenerator({ model: videoModel });
const workflow = create.Script({
context: { makeVideo },
script: `return makeVideo("A slow camera move around a mug beside a mountain lake.").video`,
});
const video = await workflow();
Calls return native video, videos, warnings, responses and provider metadata. File values expose bytes, base64 and media type. Supported frame/reference inputs, dimensions, duration, audio and other settings depend on the provider. The SDK owns direct or asynchronous generation, including polling, webhook completion, retries and downloads; the component stores no job state.
Use text/template/script/function preparation and compatible .asTool forms as with other generators. Templates render only an object prompt's text; supplied media remain native input. There is no .asStream form. Tools return file payloads; their default model output requires a calling model that accepts video files, or an explicit toModelOutput mapping. Native output files can be rendered by any UI; Casai supplies no player or framework-specific component. See the AI SDK video reference and the matrix for individual settings.
Manage conversations
Each call carries the conversation so far as its messageHistory. The ordinary call takes the new prompt or context first and the message history last, and the result's messageHistory holds that history, the new turn, and the reply. Store it and pass it to the next call. A component holds no conversation of its own, so one component serves many users.
Casai history inputs accept readonly ModelMessage[], including frozen arrays: shorthand history, .run({ messageHistory }) and .resume(history). Casai copies the outer array and borrows its messages; keep those messages unchanged while the call or stream is running. Native .generate()/.stream() parameters retain the SDK's own types.
import type { ModelMessage } from 'ai';
const chat = create.LLMAgent({
model,
instructions: 'Answer clearly and concisely.',
});
let messageHistory: ModelMessage[] = [];
const first = await chat('My project is called Orchard.', messageHistory);
console.log(first.output); // Check final output before saving an ordinary answer.
messageHistory = first.messageHistory;
const second = await chat('What is my project called?', messageHistory);
console.log(second.output);
messageHistory = second.messageHistory;
.run({ prompt, messageHistory, ...settings }) takes the same input with settings; rendered forms use .run({ context, messageHistory }).
To continue with history alone:
const continued = await chat.run({ messageHistory });
This example's chat has no configured prompt, so the call adds no new turn. If a prompt is configured, the same call prepares and appends it as usual. Execution settings and the presence of an empty context do not change prompt resolution. A positional array always means history. Supply new messages explicitly with agent.run({ prompt: newMessages, messageHistory }).
| Result field | Contents |
|---|---|
messageHistory |
The supplied messageHistory, the new turn, and all generated messages |
SDK responseMessages |
Generated messages across all model steps, without input history |
SDK response.messages / finalStep.response.messages |
The SDK's generated response messages for the final step |
Use result.messageHistory as the conversation state for the next turn. For streaming, use await result.messageHistory after consuming the stream.
All agents accept agent(messageHistory) when no payload is required, or agent(context, messageHistory) when it is. History is never rendered. The configured prompt is prepared and appended as a new turn; a string source override such as agent("Explain {{ topic }}", { topic: "embeddings" }, messageHistory) renders only that new prompt. For an authored message-array template, use configuration or .run({ prompt: templateMessages, context, messageHistory }). Do not put already rendered history into a prompt slot. Native message objects have no rendered/executed marker; the explicit source/history boundary supplies that distinction.
Configured and named prompts also accept a single native message: agent.run({ prompt: { role: 'user', content: 'Hello' } }) is equivalent to supplying a one-element prompt array. Inline templates render that message's text slots; script/function preparers may also return a single message. A bare positional object remains application context. Native .generate()/.stream() parameters retain the SDK's own types.
messageHistory is Casai's field; SDK results have no field holding the whole conversation. An SDK application keeps its input messages and appends responseMessages, but a rendered agent prepares the new turn itself, so the application never sees it. Casai adds the field without changing SDK response fields or callback payloads. Wherever Casai stores or passes a conversation, it uses the name messageHistory; messages remains only in the SDK's own APIs.
When appending to an existing SDK conversation, use SDK responseMessages. It remains generated messages only, so [...inputMessages, ...result.responseMessages] does not duplicate the input. When the SDK methods receive a complete conversation in prompt or messages, messageHistory includes it once; Casai does not guess where the new turn begins.
Fixed guidance belongs in instructions, which apply to every call. Messages returned by a script or function prompt are appended after the history. messageHistory records the conversation, not the request: if a prepareCall hook adds example turns or trims old history before sending, the stored history still holds the whole conversation.
History follows native responseMessages availability and rejection, without a separate execution-success check. It may retain partial or earlier messages after a provider failure or an error finish reason. Output parsing failure also does not erase available messages. Inspect native finish reasons and tool/approval events before deciding how to continue; resolved history is not proof of success or safe resumability. A generation call that rejects does not return a separate history handle.
For an ordinary answer, consume native output and inspect finish reasons and errors before saving history according to application policy. Schema validity alone does not certify completed tool work. For tool/approval pauses, save pending history deliberately and continue with a new invocation. Observe native error callbacks/events too; SDK limitations can retain earlier completed steps after later failure.
Casai does not persist, summarize, or truncate history automatically. Store it per conversation and manage its size in your application. Preserve tool calls with their corresponding results and approval messages when selecting history for another turn.
Render Only the New Message
Pass a new message as data in rendering context, alongside previously prepared history. Casai renders the configured template for this call and keeps the rendered prompt in the returned history:
const templatedChat = create.LLMAgent.withTemplate({
model,
prompt: 'Help with this request:\n{{ message }}',
inputSchema: z.object({ message: z.string() }),
});
let messageHistory: ModelMessage[] = [];
for (const message of ['My project is called Orchard.', 'What is my project called?']) {
const result = await templatedChat({ message }, messageHistory);
messageHistory = result.messageHistory;
console.log(result.output);
}
message is an application-chosen template variable, not a reserved argument. Its contents are data, so text containing {{ ... }} is not evaluated again as template source. Only the current context is validated and prepared; earlier rendered messages pass through unchanged. Create the agent with .asStream for the same preparation with incremental generation, then obtain history from await result.messageHistory.
If a rendered turn pauses for approval, retain its raw { message } with the pending history. The later call is templatedChat.resume(saved.history, { context: saved.context, approve: selectedIds }); the required field comes from the actual paused turn. Retain per-call toolsContext inputs too when used, and reconstruct compatible public defaults and trusted bindings. Hooks see that turn's newly prepared context without rendering it again.
For application-managed rendered conversations, store the prepared messageHistory and have the client send only the new turn's data. The SDK's complete conversation doesn't identify a new turn to render, so don't feed it through the rendered Casai call as fresh input. Native .generate()/.stream() accept that conversation literally, skip rendering and still require the agent's application context contract. To regenerate a reply, call again with the same input and the history before that turn. To continue after tool approvals, use resume(), which adds no turn. Native UI-stream consumers additionally retain their UI messages; prepared model history and original text alone do not provide the tool-part state needed to continue a UI message.
Connect application interfaces
LLMAgent forms without .asTool implement the AI SDK Agent interface through two additional methods, .generate() and .stream(). They exist for SDK compatibility: SDK helpers such as createAgentUIStreamResponse call them. They take the SDK's call arguments, not Casai's: the complete conversation as a literal prompt or messages, plus options for application context, abortSignal, timeout, and callbacks. They never prepare the configured prompt, so text they receive is never rendered. .generate() always generates and .stream() always streams, whatever the component's mode, and both return full SDK results. In your own code, use the ordinary call or .run(). An LLMAgent tool has the Tool interface instead; pass its non-tool parent or another non-tool component sharing its configuration to UI helpers.
Template, Script, and Function use native Casai contracts. They can implement operations inside a chat application's workflow, but are not directly accepted by SDK Agent UI helpers. An application can present their text or structured data through its own UI protocol; Casai does not automatically turn native values into a multipart conversation.
Agent Properties
SDK integrations can identify a non-tool LLMAgent through agent.id and agent.version, and read its registered tool definitions from agent.tools. To call the same application function from a Script, make the callable helper available in context. Agent properties and methods · Calling tools from coded components
Generation, Streaming, and the Chat UI
The SDK methods choose the mode themselves, so a streaming helper can use any LLMAgent:
const writer = create.LLMAgent({ model });
const streamer = create.LLMAgent.asStream({ model });
const incremental = await writer.stream({ prompt: 'Explain recycling.' });
for await (const text of incremental.textStream) {
process.stdout.write(text);
}
const complete = await streamer.generate({ prompt: 'Explain recycling.' });
console.log(complete.output);
.stream() delegates to SDK model streaming regardless of .asStream. .generate() delegates to SDK generation. Each starts one execution with the configured stopping condition; Casai retains the SDK's result fields, events, usage, and callbacks.
These methods accept native Agent parameters, including options for application input. Use .run() for ordinary calls with Casai settings overrides such as model or prepareCall; derive another component to change fixed contracts such as output. For a literal continuation that must skip rendering, configure or derive the component with settings outside the native call surface, then use .generate()/.stream(). Approvals and continuation
What the Chat UI Uses
The chat client sends UIMessage[] to a server handler. The SDK helper validates the messages, converts them to ModelMessage[], calls LLMAgent's .stream({ prompt: convertedMessages, ... }), and consumes the SDK event stream to produce assistant message parts. A raw native text or element stream is a different contract. See the SDK UI response helper.
Any non-tool LLMAgent whose input requirements are satisfied can serve this handler, including one with stopWhen: isStepCount(1). The limit counts model steps within a request, not chat turns. A single step can execute tools and emit UI tool parts, but cannot make another model call to write an answer using their results. Increase the limit when that follow-up is needed.
import { createAgentUIStreamResponse } from 'ai';
const chatAgent = create.LLMAgent({
model,
instructions: 'Answer clearly and concisely.',
});
export async function POST(request: Request): Promise<Response> {
const body = await request.json();
if (!body || !Array.isArray(body.messages)) {
return new Response('Expected a messages array.', { status: 400 });
}
return createAgentUIStreamResponse({
agent: chatAgent,
uiMessages: body.messages,
abortSignal: request.signal,
});
}
Wire the returned Response into your server framework and use an SDK UI client to consume it. Text, tool, reasoning, source, and file displays depend on the parts actually emitted and the application's renderers. Structured .output does not by itself define a chat widget.
For SDK UI handlers, a plain agent with request context such as language is usually sufficient. Rendered agents also support the helper, but their configured renderer is skipped and every required context field must still be supplied or defaulted. Use the rendered Casai call when the agent should prepare the new turn.
The helper supplies a literal conversation and passes application context as native options. The same inputSchema and configured context defaults apply; only source loading/rendering is skipped. SDK tools with required execution context still need configured toolsContext entries, separate from application context and runtimeContext. Undefined settings preserve configured values; native lifecycle observers compose under SDK alias precedence.
Dynamic Instructions for Chat Requests
Put shared behavior in instructions. For instructions that depend on the request, use application context and prepareCall to render a Template once, while keeping the full incoming conversation intact:
const chatInstructions = create.Template({
template: 'Answer clearly and concisely in {{ language }}.',
inputSchema: z.object({ language: z.string() }),
});
const localizedChat = create.LLMAgent({
model,
inputSchema: z.object({ language: z.string() }),
context: { language: 'English' },
prepareCall: async (request, config, context) => ({
...request,
instructions: await chatInstructions({ language: context.language }),
}),
});
await localizedChat.run({
prompt: 'What is a solar panel?',
context: { language: 'Spanish' },
});
The SDK UI helper passes the same raw context as options: { language: 'Spanish' } alongside its conversation. This prepares system instructions without rewriting user, tool, approval, or media messages. For an application that renders new user turns, separate new input from saved prepared history.
For voice interfaces, see voice session setup and the planned browser client. Keep the connection and UI lifecycle with the application; the reusable backend component prepares sessions and executes authorized tools.
Load and organize sources
Keep larger templates and scripts in files, and share helpers through context. The loader reference lists supported loader contracts.
Source Properties
Standalone Template uses template; standalone Script uses script. LLMAgent uses prompt, with the modifier determining whether it contains literal input, a template, a script, a function, or a resource name. A one-off replacement goes in the same property: as the first argument of the ordinary call, or as prompt in .run(). Other AI operations prepare the main property described in the preparation table.
Configured inline templates and scripts are compiled for reuse, with syntax errors reported when called. Loaded sources resolve on first use through Cascada's native environment cache, preserving source origin, declaring loaders, relative imports, reload policies, noCache, and invalidation. Casai adds no general compilation cache. A one-off resource name can bypass a missing configured resource.
Filters
Filters transform values using the template pipeline operator. They may be synchronous or asynchronous:
const label = create.Template({
template: '{{ title | shout }}',
filters: { shout: (value: string) => value.toUpperCase() },
});
console.log(await label({ title: 'Weekly report' }));
Loader
A loader resolves named sources for .loadsText, .loadsTemplate, and .loadsScript, as well as template/script imports and includes.
import { FileSystemLoader } from 'casai';
const loadedWriter = create.LLMAgent.loadsTemplate({
model,
loader: new FileSystemLoader('./prompts'),
prompt: 'summary.njk',
});
const summary = await loadedWriter({ text: 'A document to summarize.' });
Put a template such as Summarize this document: {{ text }} in ./prompts/summary.njk. To select another resource for one call, pass its name as the first argument or as prompt in .run().
| Loader | Use |
|---|---|
FileSystemLoader |
Read local files in Node.js; relative imports resolve from the containing file |
WebLoader |
Load sources from a base URL |
PrecompiledLoader |
Load sources precompiled with Cascada |
Custom loaders have two forms, both supported directly by Cascada:
| Form | API | Type from cascada-engine |
|---|---|---|
| Function | loader(name) |
LoaderFunction |
| Object or class | loader.load(name) |
LoaderInterface |
A plain object works; no class is required. Both forms return text, a { src, path, noCache } object, or null for a missing resource. They may return a promise. Throw for a loading failure. Plain .loadsText requires text rather than a precompiled template or script.
const sources: Record<string, string> = {
'welcome.njk': 'Welcome {{ name }}!',
};
const load = async (name: string) => sources[name] ?? null;
const loader = { load }; // Or pass the load function directly below.
const welcome = create.Template.loadsTemplate({
loader,
template: 'welcome.njk',
});
console.log(await welcome({ name: 'Ada' }));
Object/class loaders can also provide isRelative(name) and resolve(from, to) for relative paths, and on(event, handler) for load/update events. Existing getSource loaders are also supported.
Combining loaders
Use an array to try loaders in order. Use raceLoaders to try them together:
| Setting | What happens |
|---|---|
[loaderA, loaderB] |
Try A, then B only if A returns null |
raceLoaders([loaderA, loaderB]) |
Start both; use the first source found |
raceLoaders([[loaderA, loaderB], loaderC]) |
Start A and C; try B only if A misses |
Use raceLoaders when loaders hold different files, such as billing and support templates. If both hold the requested file, the first one to return it wins. Use an array when one loader should take priority.
A child normally tries its loaders before its parent's:
Child's loader setting |
What happens |
|---|---|
| A loader or array | Try the child, then the parent if the file is missing |
raceParent(loaders) |
Try the child and parent together |
overrideParent(loaders) |
Use only the child's loaders |
Omitted or undefined |
Keep the parent's loaders |
Put raceParent or overrideParent directly in loader, not inside an array or another helper. Both work without a parent. An empty array still allows parent lookup; overrideParent([]) removes the parent's loaders.
For example, with configured sharedLoader and localLoader:
import { create, raceParent } from 'casai';
const parent = create.Config({ loader: sharedLoader });
const page = create.Template.loadsTemplate({
template: 'billing/invoice.njk',
loader: raceParent(localLoader),
}, parent);
Here, localLoader and the parent's loader start together. To give the local file priority instead, use loader: localLoader.
Cascada uses the configured loaders for include, import, and other file-loading operations.
With ordinary inheritance, a parent's pages/main.njk including ./part.njk uses the child's pages/part.njk if present, then the parent's file if missing.
With raceParent, relative files stay with whichever side found the main file. If the child finds the template but only the parent has its ./part.njk, that include fails.
raceLoaders takes one array, which may be empty or contain one loader. If all loaders miss, it returns null. If none succeeds and one fails, it reports an error. An array stops on a loading error. Started loads are not cancelled.
.config.loader contains the combined loaders without the parent helpers. Use LoaderGroup for that value and LoaderInput for a setting that may use those helpers. Cascada handles caching, reload policies, and loader updates.
Render Options
renderOptions configures Cascada rendering, for example trimBlocks or standalone template HTML escaping:
const page = create.Template({
template: '<h1>{{ title }}</h1>',
renderOptions: { autoescape: true, trimBlocks: true },
});
console.log(await page({ title: 'Research & development' }));
Standalone templates default autoescape to false. All AI component source preparers disable HTML escaping, including image prompts and speech text, even when renderOptions.autoescape is true; use an explicit filter or function when your application needs escaping. Renderer options, filters, and loaders are creation-time settings. Source caches respect loader updates and noCache.
Handle failures and control execution
Cancellation and timeouts today
Pass abortSignal to .run() or native Agent methods, never reusable configuration. Casai checks it before preparation and before SDK dispatch and forwards actual signals through registered tool execution. Preparation is awaited normally. SDK timeout starts at the native execution boundary and does not cover preceding parsing, loading or rendering. Script, Template and Function accept an explicit signal for cooperative forwarding; they do not impose inherited deadlines or forcibly interrupt arbitrary code.
Configuration errors use ConfigError; invalid application input/output uses ValidationError. Cascada execution failures retain ScriptError and their cause. Native SDK/provider failures retain native behavior. Retrying an effectful workflow is an application decision; SDK model retries do not make arbitrary side effects safe to repeat.
Timeouts currently apply at the native SDK boundary and do not include Casai prompt preparation or propagate a workflow deadline to arbitrary nested components. Pass abortSignal per invocation and forward it explicitly from callbacks when calling another service. A signal requires cooperative cancellation; stopping display does not stop the work.
Model execution settings
AI components use their operation's SDK settings and retain its result fields. Follow the reference links in the component overview for full input and return contracts. Support for individual settings depends on the model and provider.
LLMAgent exposes SDK generation settings, lifecycle callbacks, and request/step preparation hooks. Its non-tool forms also implement the SDK Agent interface. The hooks are optional; SDK Agent compatibility does not depend on using them. Template, Script, and Function use their native component contracts, with application data and callable helpers in context. See cancellation for per-call signals and timeouts.
Configure settings shared by calls on the component. For example, instructions apply when a caller supplies a new prompt. Use .run() for a request-specific limit or callback. The Config tab shows which settings each form accepts at construction and invocation. LLMAgent configuration
Casai does not impose sampling defaults. An omitted setting uses SDK/provider behavior. Use current SDK setting names in configuration and .run(), such as instructions, telemetry, repairToolCall, and include; deprecated setting aliases are rejected. abortSignal is a per-call setting and is rejected in constructor configuration. For cancellation, pass an abort signal for one call:
const result = await explain.run({
context: { topic: 'solar panels' },
abortSignal: AbortSignal.timeout(10_000),
});
Lifecycle Callbacks
Callbacks are useful for recording usage, inspecting tool activity, and updating application state:
const observed = create.LLMAgent({
model,
onStepEnd: ({ stepNumber, finishReason }) => {
console.log('Step completed', stepNumber, finishReason);
},
onEnd: ({ usage }) => {
console.log('Total usage', usage);
},
});
Streaming completion callbacks require the stream to progress to completion. onChunk, onError, and onAbort apply to streaming execution. Lifecycle observers passed to .run() run alongside the configured observers; both are awaited, their failures are ignored as in the SDK, and completion order is not guaranteed. onChunk still pauses stream processing until its observers settle. Control hooks use replacement semantics: a supplied onError replaces the configured handler and preserves its retry decision; supplied preparation/repair hooks and transform lists likewise replace configured values. See SDK lifecycle callbacks.
Each LLMAgent reports its own usage through these callbacks and the SDK's usage fields. These do not add up every model call inside a Script or Template; aggregate the calls your application owns for workflow-wide reporting.
Application Context and Hooks
Use prepareCall for request-wide decisions and prepareStep for decisions based on model/tool execution so far. Both are optional LLMAgent callbacks and apply to ordinary calls, .run(), and SDK/UI calls.
| Hook signature | When it runs | What it returns |
|---|---|---|
prepareCall(request, config, context) |
Once, after context and prompt preparation | The complete editable request; spread request to retain its other settings |
prepareStep(step, config, context) |
Before each model step, starting at stepNumber: 0 |
Native partial step overrides, or undefined |
The arguments have distinct roles:
requestcontains editable SDK settings andmessages: the rendered/literal conversation plus history. It contains no application context or custom options.stepcontains native step information, includingstepNumber, completedsteps, and current messages/model; it is not a complete request to spread back.configis the flat configuration plus supported call overrides, resolved for this invocation before the hook. Itscontextincludes caller overrides of public defaults, before parsing; itspromptis the selected source.contextis the final prepared application object, after merging defaults, input-schema processing and private bindings. Rendered calls pass this same object to their prompt preparer. Defaults, stripping and transforms can make it differ fromconfig.context. SDK tool arguments enter this object; their raw form is not reconstructed inconfig.
Both hooks receive the same config/context objects throughout the invocation; evolving state is in step. Reusable hooks can annotate an unused config parameter as unknown, or declare only the settings they consume, so unrelated config types do not become dependencies. Callbacks may ignore unused arguments. Native one-argument step callbacks work; native call hooks that read options need an explicit adapter to the third argument.
One schema covers data used by both the renderer and hooks. Here, model supports tools and search is an application-provided tool:
import { isStepCount } from 'ai';
const researcher = create.LLMAgent.withTemplate({
model,
prompt: 'Research this question: {{ question }}',
context: { language: 'English' },
inputSchema: z.object({
question: z.string(),
language: z.string(),
}),
tools: { search },
stopWhen: isStepCount(2),
prepareCall: (request, config, context) => ({
...request,
instructions: `Answer in ${context.language}.`,
}),
prepareStep: ({ stepNumber }) => ({
toolChoice: stepNumber === 0
? { type: 'tool', toolName: 'search' }
: 'none',
}),
});
await researcher({
question: 'What are practical uses of perovskite solar cells?',
language: 'Spanish',
});
The first step requests search; if the loop continues, the second answers with tools disabled. This policy applies to each invocation: a continuation restarts at step zero and would request search again. A hook intended for resumable workflows should use the conversation or application context to decide whether another search is needed. Context is prepared once, before rendering or either hook, including on plain-text agents with no renderer. No separate options object or schema is needed.
SDK calls use options as the native name for that same raw context. They apply the same inputSchema and configured defaults, but skip loading/rendering the configured prompt. Required fields remain required, even if only the skipped renderer uses them:
await researcher.generate({
prompt: 'Research perovskite solar cells.', // Literal conversation.
options: { question: 'Perovskite solar cells', language: 'Spanish' },
});
Pass messages: [] when prepareCall supplies the entire conversation. JavaScript calls that omit both prompt and messages also reach the hook with an empty conversation. Context validation still applies, and the SDK rejects an empty final request.
The types keep that boundary explicit:
| Surface | Application data |
|---|---|
Casai configuration and .run() |
context; custom options and callOptionsSchema are rejected |
| Preparation hooks | Third argument context; no custom options in request/config |
| Native SDK methods and UI helpers | options carries the same raw context input |
Casai's .generate()/.stream() let you omit options when no context input remains required after defaults; otherwise its required fields must be supplied. Omission still runs the shared input preparation. SDK helpers forward options to Casai so a reusable agent can receive request-specific data. Casai applies context's shallow merge, validation and private-binding rules, then consumes it before calling generateText/streamText. It is not automatically sent to the model or registered tools' toolsContext.
The call hook can change the admitted SDK request settings, including timeout, streaming error handling/transforms/retries and sandbox. Its complete return wins on every entry path, including explicit SDK/UI settings; omitted or undefined editable fields are not restored. Spread request to retain them. A replacement must include toolsContext when its declared tools require context. Use .run({ prepareCall: anotherHook }) to replace its policy. SDK/UI callers use a differently configured agent for different policy: unlike native ToolLoopAgent, their timeout/transform/sandbox settings remain editable by the hook.
Fixed output, caller cancellation, composed observers, approval policy/signing (toolApproval and experimental_toolApprovalSecret) and the whole telemetry setting stay outside the editable request. Configure these normally; supported .run() overrides still apply. Use the native toolApproval callback for dynamic approval decisions. prepareStep keeps native partial overrides, with no timeout override.
Changed request messages do not rewrite original result history. This includes a hook that creates the entire conversation from empty input: only response messages are then recorded. Supply a persistent new turn through call input or a prompt preparer. Step hooks retain SDK rules: model/tool-choice overrides apply to one step; instruction/message/runtime-context/tool-context replacements carry forward. Bound Casai tool context stays fixed; see tool execution context.
Both hooks may be asynchronous and call ordinary components; see dynamic instructions. They read explicit invocation cancellation from context._toolOptions.abortSignal; SDK-internal timeout signals are not exposed there. request.tools contains the authored tool entries from resolved config, before automatic dispatch binding; explicitly bound descriptors stay bound. Context tool helpers keep their earlier bindings even if the hook changes model tools/context. Return replacements and copy changed nested paths; do not mutate configuration or borrowed request/context data. Hooks never rewrite the component's .config; there is no deep cloning or freezing. The full config argument is not redacted, including configured signing keys. Inherited hooks must remain compatible with derived configuration and parsed context.
For example, with detail declared in inputSchema, a call hook can choose its timeout:
prepareCall: (request, config, context) => ({
...request,
timeout: context.detail === 'deep' ? 60_000 : 10_000,
})
Currently, the hook-selected timeout is forwarded to the native SDK and starts at that execution boundary. Including preparation and inheriting parent deadlines are planned capabilities. See cancellation and timeouts.
Planned workflow deadlines
Work in progress: the inherited-deadline behavior in this subsection is planned. Use the explicit cancellation and native SDK timeout behavior above for current applications.
Pass abortSignal or timeout through .run() to control an invocation. SDK operations retain their own supported timing and cancellation controls; those controls vary by operation. Nested component calls inherit the parent's deadline; use a shorter local timeout to bound a particular operation.
A numeric timeout, or an SDK timeout object's totalMs, covers preparation and execution from invocation start. The earlier of the local and parent deadlines applies. prepareCall may shorten, extend or remove the local total while the call is still active, but cannot extend a parent deadline or revive an expired call. Already-started work keeps its captured deadline; later children inherit the updated one. SDK step/tool/chunk limits retain their native meanings.
timeout is replaced as a whole. Returning timeout: { stepMs: 5_000 } removes an earlier total limit, including the local total deadline. To add a step limit while retaining the total and other limits:
prepareCall: request => ({
...request,
timeout: {
...(typeof request.timeout === 'number'
? { totalMs: request.timeout }
: request.timeout),
stepMs: 5_000,
},
})
LLMAgent passes invocation cancellation to the SDK and its tools. Supply a request signal or AbortSignal.timeout(...) per call, or call controller.abort() on a supplied controller. Reusable component configuration rejects abortSignal; cancellation belongs to an invocation. Function callbacks and .withFunction preparers receive the signal in their execution options and must forward it to supported operations such as fetch or another SDK call. A Script/Template SDK tool entry also captures that signal for its injected registered tools, just as an explicit .run({ abortSignal }) does. Forwarding does not interrupt rendering or reach arbitrary functions/components supplied in context. Stopping display alone is not cancellation.
The deadline follows nested component calls, including calls made from JavaScript Function callbacks. At an SDK boundary, the remaining time is passed to the SDK; ordinary step/tool/chunk timeout limits still apply.
A timeout rejects the wait. JavaScript or rendering that does not support cancellation may continue in the background; a timeout is not a rollback. New nested calls after expiry reject before execution. Returned streams keep their deadline for the execution lifetime.
Usage
Each LLMAgent result reports its token usage through the SDK's usage and totalUsage fields and onEnd callbacks. These describe that model invocation, not the sum of every model called elsewhere in a Script or Template. Aggregate the calls your application owns when reporting workflow-wide usage.
Errors and Retries
Wrap creation and await component(...) in try/catch when handling failures. Some invalid configurations throw during creation; input preparation and generation can fail during invocation.
| Error source | How to inspect it |
|---|---|
| Invalid configuration or unsupported schema/binding contracts, even when discovered lazily | ConfigError, exported from casai |
Invalid call arguments or Casai input/context/output/stream-element validation, including unknown approvals in resume(), unknown tools in executeTool(), and repeated handoff of a known ReadableStream input to a streaming component |
ValidationError, exported from casai |
| Template or script compilation/execution | TemplateError or ScriptError; inspect cause for the underlying failure |
| Provider requests or structured LLMAgent output | SDK error types and their documented instance checks |
| Streaming generation or tool execution | Full-stream error / tool-error parts, callbacks, and promise/iterator failures |
Cascada native stream/tstream failure |
Cascada terminates at the first error after the valid prefix; Casai forwards it unchanged |
| Cascada complete return failure | The engine returns its poison/failure outcome instead of a partially failed object |
| Full-stream source failure | All consumers stop at that failure; recovery cannot resume a closed producer |
| Paused or unfinished LLMAgent tool execution | Tool adapter rejects with NoOutputGeneratedError; ordinary calls retain native output/error semantics |
| Native stream producers | Iterator failures and native completion/validation errors |
Injected tool calls use Casai's ValidationError for argument and tool-context validation, including when the registered tool is a native SDK tool. Private-context validation details remain in cause; the public message identifies the failed stage without exposing the rejected context. This matters when a coded workflow is itself a model tool, because execution error messages can become tool output sent to the model. Native SDK-owned validation and errors thrown by tool implementations retain their native behavior. Treat error causes as trusted diagnostics rather than model-facing output.
ValidationError and ConfigError are distinct classes. Use their .isInstance(error) guards across compatible package copies; runtime-validation catches that previously used ConfigError must now use ValidationError. All Casai error classes live in src/errors.ts.
For streaming, handle event errors as well as thrown errors. This example uses the full event stream so tool failures are visible alongside text:
const controller = new AbortController();
try {
const stream = await create.LLMAgent.asStream({ model }).run({
prompt: 'Explain how batteries are recycled.',
abortSignal: controller.signal,
});
for await (const part of stream.stream) {
switch (part.type) {
case 'text-delta':
process.stdout.write(part.text);
break;
case 'error':
case 'tool-error':
console.error(part.error);
break;
case 'abort':
console.log('Generation cancelled.');
break;
}
}
} catch (error) {
console.error('Request failed:', error);
}
For cancellation setup and nested deadlines, see Cancellation, Timeouts, and Usage.
maxRetries controls SDK request retries; it does not restart a Casai script or preparation. Streaming recovery uses native settings such as streamRetries. Output, stream events and callback errors retain SDK behavior; Casai adds no retry buffer or error-cause recovery. A finished text stream alone does not prove success.
Type-check and test workflows
Casai infers input types from schemas, context, and function signatures. Output specifications determine the type of generated values; tool maps retain typed arguments and results. Use import type for SDK types such as ModelMessage and ToolExecutionOptions.
Use ComponentConfig<'Embedder'> to annotate an ordinary Embedder configuration. The second parameter selects a source the factory supports, and the third selects delivery. For example, ComponentConfig<'Transcriber', 'audio-resource'> describes settings for Transcriber.loadsAudio. Use ComponentConfig<'SpeechGenerator', 'text', 'stream'> with SpeechGenerator.asStream. Use satisfies to preserve specific schema types and configured defaults. Tool factories infer their settings through .asTool.
Completed audio annotations keep each operation's selector: raw Transcriber settings require inputAudioFormat, prepared file transcription requires fileAudioTarget, and collected SpeechGenerator settings require an object outputFormat. This keeps a broadly annotated configuration callable without mixing incompatible native settings. Inferred factories can still receive raw formats at invocation or select collected speech from non-string text. Function-mode annotations receive ordinary execution context; use inference or satisfies to retain exact application fields.
LLMAgentConfig describes authored settings with the default text source. A function accepting that annotation can pass it directly to LLMAgent. Use ComponentConfig<'LLMAgent', Source> with the matching factory modifier for an already selected source, such as 'text-name' with .loadsText or 'function' with .withFunction. These annotations cannot erase a fragment's different source selection. Loaded-source annotations require a loader; an unfinished reusable fragment can still use Config.loadsText and receive its loader from the finished component.
ComponentConfig defaults to the component's own source mode. For Template and Script, that is inline source: their finished annotations require template or script. Use 'async-template-name' or 'async-script-name' with the matching loading modifier for a loaded source; those annotations require a loader and permit the file name at invocation. TemplateConfig, ScriptConfig and their tool counterparts describe inline settings. ScriptConfig keeps script optional, so a wrapper using it must preserve that field's required presence before constructing an inline Script.
Optional fields remain optional after annotation. Even if a particular value supplied a prompt, a wrapper accepting LLMAgentConfig must supply one at the call or retain its required presence in the type. Inference and satisfies preserve more information about configured prompts, schemas and tool names.
import type { ComponentConfig, LLMAgentConfig } from 'casai';
function answer(config: LLMAgentConfig, prompt: string) {
return create.LLMAgent(config)(prompt);
}
function answerFromFile(config: ComponentConfig<'LLMAgent', 'text-name'>, name: string) {
return create.LLMAgent.loadsText(config)(name);
}
function prepareAnswer(config: ComponentConfig<'LLMAgent', 'function'>) {
return create.LLMAgent.withFunction(config);
}
function renderGreeting(config: ComponentConfig<'Template'>) {
return create.Template(config)();
}
await answer({ model }, 'Explain solar energy.');
await answerFromFile({ model, loader: { load: () => 'Explain solar energy.' } }, 'question');
await prepareAnswer({ model })(() => 'Explain solar energy.');
await renderGreeting({ template: 'Hello.' });
Keep tool configuration inferred. satisfies LLMAgentConfig can check ordinary settings while preserving the actual prompt, schema and absence of streaming before passing the value to .asTool. A broad LLMAgentConfig annotation permits streaming and erases schema details, so it is not a tool configuration type.
import type { LLMAgentConfig } from 'casai';
const toolSettings = {
model,
prompt: 'Explain solar energy.',
inputSchema: z.object({}),
} satisfies LLMAgentConfig;
const explainSolarEnergy = create.LLMAgent.asTool(toolSettings);
const classify = create.LLMAgent.withTemplate({
model,
inputSchema: z.object({ text: z.string() }),
prompt: 'Classify this message: {{ text }}',
output: Output.choice({ options: ['question', 'feedback', 'other'] }),
});
const classification = await classify({ text: 'How can I reset my password?' });
// classification.output is 'question' | 'feedback' | 'other'.
// @ts-expect-error: text must be a string.
await classify({ text: 42 });
Inheritance checks the final configuration. A per-call override preserves the component's input and result contracts, so changing output schemas or tool types requires creating a component with that new contract. Native SDK options uses the same raw application-input contract as Casai context; bodies and hooks receive the prepared context's parsed types.
Testing Workflows
Test orchestration with deterministic helpers in context, without making model calls. A test double only needs to supply the values that the workflow consumes:
import assert from 'node:assert/strict';
const workflow = create.Script({
inputSchema: z.object({ topic: z.string() }),
schema: z.object({ summary: z.string() }),
context: {
summarize: async ({ topic }: { topic: string }) => ({
output: `Summary of ${topic}`,
}),
},
script: `
return { summary: summarize({ topic: topic }).output }
`,
});
assert.deepEqual(await workflow({ topic: 'recycling' }), {
summary: 'Summary of recycling',
});
To exercise the LLMAgent's full model/tool protocol, supply an AI SDK mock model through model; see SDK testing. Test concurrent .run() calls with distinct inputs when verifying invocation isolation, and consume streams in tests that assert final results or completion callbacks. Type-check TypeScript examples separately from executing them.
Examples and further reading
The examples below cover classification, embedding and retrieval. For complete workflow walkthroughs, browse the Casai blog. See also Casai examples, the Smart DB Dashboard, tutorials, CascadaScript and Cascada templates.
Classify and evaluate with Decision
Decision answers named choice, boolean, score, or bounding-box questions against shared state. Use it to route requests, apply a rubric, or evaluate several related questions. It uses the AI SDK's experimental experimental_decide API.
const route = create.Decision({
model: decisionModel,
questions: {
department: {
type: 'choice',
instructions: 'Select the team responsible for this issue.',
criteria: {
returns: 'Damaged products and returns',
billing: 'Payment problems',
},
},
},
});
const decision = await route('My order arrived damaged.');
console.log(decision.answers.department.choice);
console.log(decision.answers.department.probabilities); // When supplied by the provider.
Configure the model and question definitions, then pass the state to each call; .run({ state, ...settings }) adds per-call settings. Native state can be text, a JSON object, or an ordered array of text/file/JSON parts. Inline templates render explicit text parts and preserve the other parts; JSON parts stay literal. Script/function preparers can produce any native state. The result retains typed answers, any distributions, usage, metadata, and SDK refusal/error behavior.
Decision performs a decision request and does not run a tool loop. It can itself be exposed as a tool with .asTool. For choosing a value as part of a language-generation workflow, an LLMAgent can instead use Output.choice(); that uses the generation operation.
See SDK Decisions for question types, state formats, model support, and results.
Embed texts for retrieval
Embedder converts text into vectors for semantic search, similarity, clustering, and retrieval. Pass one string or an array directly:
const embedder = create.Embedder({ model: embeddingModel });
const one = await embedder('First document');
const many = await embedder(['First document', 'Second document']);
console.log(one.embedding); // number[]
console.log(many.embeddings); // number[][], in input order
For retrieval, keep each batch vector alongside its input document. The SDK handles batch splitting and returns the vectors in input order. Single and batch return fields
Use input for either one string or an array in configuration and .run(). Per-call settings go through .run():
await embedder.run({ input: ['First document', 'Second document'], maxParallelCalls: 2 });
await embedder.run({ input: 'Another document', abortSignal: AbortSignal.timeout(5_000) });
Use embedder.run() when input is already configured. Supply input to replace it for a call. Embedder input and overrides
All input modifiers and .asTool are supported. .withText keeps the plain call form: pass a string or string array directly. With a template, script, function or loading modifier, input holds the source and ordinary calls supply preparation context. Text loaders and templates produce one string; a script or function preparer can return a string or string array. A plain tool, including .withText.asTool, declares { input } in its input schema; a prepared tool declares the context fields its source consumes.
As a tool, an Embedder returns vectors. Models can't compute with them, so this is an uncommon use, mainly for tool workflows where the application or another step consumes the vectors.
To use the vectors in an answer workflow, see Embedding and RAG integration.
Rank retrieved candidates
Reranker orders candidate documents by relevance to a query. Use it after keyword, vector, or hybrid retrieval to select useful context for an LLMAgent or improve search results.
const reranker = create.Reranker({ model: rerankingModel });
const ranked = await reranker.run({
query: 'How are damaged orders replaced?',
documents: [
'Contact support with a photo of the damage to request a replacement.',
'You can update your payment card in account settings.',
'Keep the original packaging until your claim is resolved.',
],
topN: 2,
});
console.log(ranked.rerankedDocuments);
console.log(ranked.ranking); // Original indices and relevance scores.
If the same candidate set serves several queries, configure documents and call reranker(question). For candidates retrieved per query, a preparer can return both query and documents. Call forms · Document overrides
As a tool, the model supplies only the query. Candidates come from configured documents or from a preparer, so the model never copies documents into its tool arguments. A function preparer can fetch candidates for each query, making one component a retrieve-and-rerank tool:
const findPolicy = create.Reranker.withFunction.asTool({
model: rerankingModel,
description: 'Find the policy passages most relevant to a question.',
inputSchema: z.object({ question: z.string() }),
topN: 3,
query: async ({ question }) => ({ query: question, documents: await searchPolicies(question) }),
});
searchPolicies supplies candidates from your index. Each ranking entry includes the original document, ready to pass to the answering agent. Use originalIndex when you need to look up information held separately from the document. Reranker tool return
Embedding and RAG Integration
Retrieval-augmented generation (RAG) supplies relevant documents to an LLMAgent before it answers:
question -> embedding/search -> candidate documents -> reranking -> LLMAgent answer
Use Embedder to index document text and embed search queries with the same model. Your vector store or search service owns storage and retrieval. Reranker can improve the order of the retrieved candidates before they enter the prompt. Handle an empty result before generating an answer, and keep the selected sources available to the caller.
From retrieval to grounded answers combines semantic and keyword searches in a concurrent workflow, then ranks their results and generates an answer. For component usage, see Embedder and Reranker.
Migrating existing applications
Replace race(loaders, groupName?) with raceLoaders(loaders). Group names and the RaceGroup/RaceLoader types are removed. .config.loader now keeps nested arrays and races; use LoaderGroup for its type. LoaderInput also accepts raceParent(...) and overrideParent(...).
Child files can now replace files included or imported by a parent's template. Previously, relative files always came from the loader that supplied the template. With raceParent, relative files stay on the side that found the main file; they do not fall back between child and parent.
LLMAgent replaces TextGenerator, TextStreamer, ObjectGenerator, and ObjectStreamer; the old exports and types are removed. Use .asStream for streaming and native Output.object, Output.array, Output.choice, or other SDK output specifications for structured results. Use native .output for parsed output and .textStream for live text.
Await streaming component calls before accessing the SDK result. Await .output for completed streaming output; iterate .textStream for live text. Use prompt for configured messages, messageHistory for call history, and instructions for system instructions. Rendered positional calls place context before history. Stable lifecycle names are onEnd and onStepEnd instead of onFinish and onStepFinish.
Component reference
Each component is described once. Source modifiers, tool delivery and streaming reuse the shared contracts below. Conditions apply only to the supported forms listed for that component. Choose one delivery: ordinary, .asTool or .asStream; tool and stream delivery cannot be combined.
- Config
- Context
- Template
- Script
- Function
- LLMAgent
- Decision
- Embedder
- Reranker
- ImageGenerator
- Transcriber
- SpeechGenerator
- Translator
- VideoGenerator
- VoiceAgentClient
- VoiceAgentBackend
Config
Define common settings once and pass them as a parent when creating components. For example, several agents can share a model and tools, while each supplies its own instructions. A child inherits omitted settings and can replace individual values. Context and tool maps merge by key.
Config supports the same source selectors as components, followed by compatible .asTool or .asStream modifiers. For example, Config.withTemplate.asTool selects template preparation and tool mode for its consuming component. Plain Config preserves an inherited mode without selecting a default.
A Config is a reusable settings object; it does not execute a task. It may leave settings incomplete until a component is created. The combined settings must fit that component, so unrelated options from different component types cannot be mixed. All modes are selected through modifiers; promptType, streaming and asTool are not configuration properties.
Input: A partial configuration and an optional compatible parent.
Returns: A reusable configuration object.
Configuration and supported forms
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool, .asStream |
.withAudio |
Ordinary, .asTool, .asStream |
.withText |
Ordinary, .asTool, .asStream |
.withTemplate |
Ordinary, .asTool, .asStream |
.withScript |
Ordinary, .asTool, .asStream |
.withFunction |
Ordinary, .asTool, .asStream |
.loadsAudio |
Ordinary, .asTool, .asStream |
.loadsText |
Ordinary, .asTool, .asStream |
.loadsTemplate |
Ordinary, .asTool, .asStream |
.loadsScript |
Ordinary, .asTool, .asStream |
Source modifiers: .withAudio, .withText, .withTemplate, .withScript, .withFunction, .loadsText, .loadsTemplate, .loadsScript, .loadsAudio
The inheriting component must support every selected modifier and setting. Streaming and tool mode cannot be combined.
| Can inherit these modifiers | Supported configuration forms |
|---|---|
| Template | default source + Ordinary, .asTool; withTemplate + Ordinary, .asTool; loadsTemplate + Ordinary, .asTool |
| Script | Ordinary + default source, withScript, loadsScript; .asTool + default source, withScript, loadsScript |
| Function | default source + Ordinary, .asTool |
| LLMAgent | All except loadsAudio |
| Decision | All except .asStream; Ordinary + loadsAudio; .asTool + loadsAudio |
| Embedder | All except .asStream; Ordinary + loadsAudio; .asTool + loadsAudio |
| Reranker | All except .asStream; Ordinary + loadsAudio; .asTool + loadsAudio |
| ImageGenerator | All except .asStream; Ordinary + loadsAudio; .asTool + loadsAudio |
| Transcriber | All except withTemplate, loadsText, loadsTemplate |
| SpeechGenerator | All except loadsAudio |
| Translator | All except withTemplate, loadsText, loadsTemplate |
| VoiceAgentBackend | All except .asTool; .asStream; Ordinary + loadsAudio |
| VoiceAgentClient | default source + Ordinary |
| VideoGenerator | All except .asStream; Ordinary + loadsAudio; .asTool + loadsAudio |
| Group | Properties | Available in |
|---|---|---|
| Common Casai configuration | inputSchema, context, debug, description, tools, toolsContext |
All supported forms |
| Source preparation | filters, renderOptions, loader, mediaSettings, fileAudioTarget |
All supported forms |
| Remaining AI SDK properties | inputAudioFormat |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Remaining AI SDK properties | providerOptions |
.asTool |
| Call or method | Available in |
|---|---|
Config |
All supported forms |
withText |
All supported forms |
withTemplate |
All supported forms |
withScript |
All supported forms |
withFunction |
All supported forms |
loadsText |
All supported forms |
loadsTemplate |
All supported forms |
loadsScript |
All supported forms |
loadsAudio |
All supported forms |
asTool |
Ordinary, .asTool |
asStream |
All except .asTool |
config |
All supported forms |
Results
Behavior: A reusable configuration object.
Examples
Config.ts
import { Config, LLMAgent } from 'casai';
import { type LanguageModel } from 'ai';
// Every inheriting component must support the selected modifiers and settings.
export async function shareDeliverySettings(model: LanguageModel) {
const shared = Config({
model,
instructions: "Northstar: Write a short delivery update.",
prompt: "Write a delivery update for Ada.",
});
// LLMAgent supports this selection; override just the outlet's instructions.
const outlet = LLMAgent({
instructions: "Northstar Outlet: Write a short delivery update.",
}, shared);
const result = await outlet();
return result.text;
}
Context
Context gives a component the values and services it needs to work: a customer name, order details, a database client or a helper function. Templates read these values by name; scripts and functions can use them to prepare input or perform work.
Fields declared in inputSchema are public inputs. Their configured values act as defaults, and supplied input can override them before validation. Other configured fields remain private dependencies that callers and AI tool arguments cannot replace. Context is an ordinary application object, not a component you construct or run.
Input: An application object containing public defaults and private dependencies.
Returns: Application data passed to a component.
Configuration and supported forms
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary |
| Group | Properties | Available in |
|---|---|---|
| Common Casai configuration | context, inputSchema, toolsContext |
All supported forms |
| Component behavior | toolContextSchema |
All supported forms |
| Invocation reference | _toolOptions |
All supported forms |
Results
Behavior: Application data passed to a component.
Examples
Context.ts
import { Function, z } from 'casai';
// Context holds application values and private dependencies.
export async function quoteDeliveryWithContext() {
const context = {
currency: 'GBP',
shipping: (weightKg: number) => 4 + Math.ceil(weightKg) * 0.5,
};
const quote = Function({
context,
inputSchema: z.object({ weightKg: z.number().positive() }),
execute: ({ weightKg, currency, shipping }) => ({
amount: shipping(weightKg), currency,
}),
});
// Only weightKg is public; callers do not replace shipping or currency.
return await quote({ weightKg: 2 });
}
Template
Combine a reusable text layout with values from context to create prompts, messages, reports or other text. Cascada uses the same template syntax as Nunjucks: insert values with {{ name }}, repeat content with loops, choose sections with conditions and reuse blocks with macros. Rendering itself needs no AI model.
A template returns the completed string. It can call context helpers or registered tools, and Cascada can resolve independent expressions concurrently. Keep the source inline or load the same template from a .cat resource.
Input: Cascada Template text and a context object supplying its variables.
Returns: The rendered text.
Configuration and supported forms
Main input: template
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool |
.loadsTemplate |
Ordinary, .asTool |
Default source: The template value contains Cascada Template text. Casai fills in the template variables from the context object. For example, Hello {{ name }} with context: { name: "Ada" } produces Hello Ada.
Source modifiers: .withTemplate, .loadsTemplate
| Group | Properties | Available in |
|---|---|---|
| Common Casai configuration | inputSchema, context, debug, description, tools, toolsContext |
All supported forms |
| Source preparation | filters, renderOptions, loader |
All supported forms |
| Required settings | template |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Remaining AI SDK properties | providerOptions |
.asTool |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior: Renders variables, loops, conditions and macros in a Cascada Template. Independent expressions may run at the same time. Returns one completed string.
Tool execution output:
.asTool: The rendered string.
Examples
Template.ts
import { Template, z } from 'casai';
// Write a delivery update for the customer.
export async function writeDeliveryUpdate() {
// Replace this sample lookup with your application service.
const deliveryDay = async () =>
'Friday';
const deliveryUpdate = Template({
context: { company: 'Northstar', deliveryDay },
inputSchema: z.object({ name: z.string(), orderId: z.string() }),
template: `{{ company }} delivery update
Hello {{ name }}, order {{ orderId }} is due {{ deliveryDay() }}.
Track it using the link in your order confirmation.
`,
});
const result = await deliveryUpdate({ name: 'Ada', orderId: 'N-1042' });
return result;
}
Script
Use Script as the orchestrator for a workflow: read application data, call components or tools, make decisions and combine their results. Its Cascada code implements the logic, while the components it calls perform the individual tasks. Independent operations run concurrently, so unrelated lookups can proceed at the same time.
A script returns the value you choose, such as text, an object or a list. An optional schema validates the result. Keep the code inline or load a .cas resource. Use ! to sequence operations whose side effects must happen in order.
Input: Cascada Script code and a context object whose fields become script variables.
Returns: The returned value, validated by schema when supplied.
Configuration and supported forms
Main input: script
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool |
.loadsScript |
Ordinary, .asTool |
Default source: The script value is Cascada Script code. Fields of the context object are available as variables. The script’s return value is the component’s result.
Source modifiers: .withScript, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Common Casai configuration | inputSchema, context, debug, description, tools, toolsContext |
All supported forms |
| Source preparation | filters, renderOptions, loader |
All supported forms |
| Component-specific and adapted behavior | schema |
All supported forms |
| Required settings | script |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Remaining AI SDK properties | providerOptions |
.asTool |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior: Script implements workflow logic. Independent operations run concurrently. A returned JavaScript iterable can use streamSchema or textStreamSchema; native Cascada stream channels are not exposed here.
Tool execution output:
.asTool: The validated return value. If its schema declares a stream, the tool collects it into a string or array; the stream must end.
Examples
Script.ts
import { Script, z } from 'casai';
// Combine order and shipping information. Independent lookups run concurrently.
export async function summarizeOrder() {
const getOrder = async (orderId: string) => ({ orderId, subtotal: 48 });
// Replace this sample lookup with your application service.
const getShipment = async () =>
({ cost: 4, deliveryDay: 'Friday' });
const orderSummary = Script({
context: { getOrder, getShipment },
schema: z.object({
orderId: z.string(),
total: z.number(),
deliveryDay: z.string(),
}),
inputSchema: z.object({ orderId: z.string() }),
script: `var order = getOrder(orderId)
var shipment = getShipment()
return {
orderId: orderId,
total: order.subtotal + shipment.cost,
deliveryDay: shipment.deliveryDay
}
`,
});
const result = await orderSummary({ orderId: 'N-1042' });
return result;
}
Function
Wrap application logic in a reusable component with an execute function. Use it for calculations, database lookups, service calls or any task best expressed in JavaScript or TypeScript. The function receives prepared context containing validated public input, configured private dependencies and any registered tool helpers.
The implementation can return a value directly or await asynchronous work. Casai returns that value, applying an output schema when one is configured. Expose the function as a tool when an AI agent should be able to call it with declared arguments.
Input: Parsed application input plus configured private dependencies.
Returns: The JavaScript return value, awaited and parsed by schema when supplied.
Configuration and supported forms
Main input: execute
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool |
| Group | Properties | Available in |
|---|---|---|
| Common Casai configuration | inputSchema, context, debug, description, tools, toolsContext |
All supported forms |
| Component-specific and adapted behavior | schema |
All supported forms |
| Required settings | execute |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Remaining AI SDK properties | providerOptions |
.asTool |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior: execute receives one prepared context object, including registered helpers and _toolOptions. It may be synchronous, asynchronous, or return a schema-declared stream.
Tool execution output:
.asTool: The parsed return value; declared finite streams are collected for tool execution.
Examples
Function.ts
import { Function, z } from 'casai';
// Calculate a delivery quote from package weight and service.
export async function quoteDelivery() {
// Replace this sample lookup with your application service.
const getRates = async () =>
({ standard: 4, express: 9 });
const deliveryQuote = Function({
context: { getRates },
schema: z.object({ amount: z.number(), currency: z.literal('GBP') }),
inputSchema: z.object({
weightKg: z.number().positive(),
service: z.enum(['standard', 'express']),
}),
execute: async ({ weightKg, service, getRates }) => {
const rates = await getRates();
return {
amount: rates[service] + Math.ceil(weightKg) * 0.5,
currency: 'GBP' as const,
};
},
});
const result = await deliveryQuote({ weightKg: 2, service: 'express' });
return result;
}
LLMAgent
Generate answers, summaries, drafts or structured data from a prompt using an AI language model. Supply instructions and content directly, or prepare them with a template, script or function. An output specification can request an object or another supported structured result. Registered tools let the model retrieve information and perform tasks; configure the stopping condition when it should continue across several model and tool steps.
The completed result includes the generated output and native SDK metadata. Casai also returns messageHistory for later turns. Use resume() to continue a conversation paused for tool approval without preparing the prompt again.
Input: A prompt, values from context and optional conversation history.
Returns:
generateText: The native SDK result with parsed output and Casai messageHistory..asStream: A live SDK result; consume its streams and await final output and history.
.asStream: Generate a response while making text, structured-output updates and tool events available as they arrive. Streaming is useful for chat and other interactive interfaces where readers should see progress before the full response is ready. Prompts, input preparation and tool calling work with the same underlying AI SDK generation flow.
Consume the parts your application needs and await the final output or messageHistory when the response is complete. Partial structured values are still being built and do not establish that the finished output matches its schema. The stream and final values belong to the same execution.
Configuration and supported forms
Main input: prompt
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool, .asStream |
.withTemplate |
Ordinary, .asTool, .asStream |
.withScript |
Ordinary, .asTool, .asStream |
.withFunction |
Ordinary, .asTool, .asStream |
.loadsText |
Ordinary, .asTool, .asStream |
.loadsTemplate |
Ordinary, .asTool, .asStream |
.loadsScript |
Ordinary, .asTool, .asStream |
Default source: The text or messages to send to the model.
Source modifiers: .withText, .withTemplate, .loadsText, .loadsTemplate, .withScript, .withFunction, .loadsScript
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
id |
All except .asTool |
version |
All except .asTool |
tools |
All except .asTool |
resume |
All except .asTool |
generate |
All except .asTool |
stream |
All except .asTool |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior:
-
generateText:Read
outputfor the final step’s parsed value. Casai addsmessageHistoryto the SDK result. Use it to save the conversation or continue a paused turn.With an omitted or undefined
output, or withOutput.text(), the value is a string. An object, array, choice, JSON or custom SDK Output returns its parsed type. An optional specification includes the string fallback in the inferred type. The caller owns any iterable returned by a custom parser. A structured generation can reject during parsing before it returns a result.Inspect
stepsfor the completed model steps andfinalStepfor the last one. When tools participate, checkfinishReason,rawFinishReasonand any pending approvals or tool results before treating the task as finished. Even schema-valid output can accompany a pause. -
.asStream:The stream views and final values share one native execution. Use
textStreamfor live text,streamfor execution events, andawait result.outputfor the final step’s parsed value.The
outputfield is promise-like. It resolves to a string for omitted or undefined output and forOutput.text(), or to the parsed type of the configured Output. An optional specification includes the text fallback. The caller owns any iterable produced by a custom parser.Use
partialOutputStreamfor values still being assembled orelementStreamfor elements when the output specification supports them. Whole-result schema validation occurs on the final output.stepsandfinalStepresolve to completed SDK records.messageHistoryresolves independently of final output parsing.
Tool execution output:
-
.asTool:SDK tool execution and injected tool calls return the completed text or parsed structured application value. A custom
toModelOutputreceives that value. Direct calls and.run()on the same component return the full SDK generation result, includingfiles,toolResultsandmessageHistory.A nested agent may take several model steps in one tool call. A provider
pause_turn, an error finish, or outstanding tool or approval work from this invocation rejects withNoOutputGeneratedError. Local calls and provider calls with deferred results need a matching result. A provider approval needs its matching decision sent on a scheduled step or a result that settles the call. An automatic decision alone cannot settle another approval ID. These checks include decisions supplied byprepareStepand cover work emitted by this invocation. Earlier input history follows the SDK’s handling.If any
stopWhencondition cuts off another eligible step, the tool rejects even if every result is present and the output matches its schema. This applies to the default limit, custom predicates and intentional terminal-tool conditions. Finishing naturally on the last allowed step succeeds. Casai uses the SDK’s stop decision without calling the predicate again.Native output and parsing errors propagate to the parent tool loop. The SDK rejects a
tool-callsending or empty non-stop output. Empty text on a completedstopis valid, and nonempty truncated output still follows the output parser. A failed inner tool call supplies no resumable history. To return selected files as a tool result, call an ordinary agent from a Function tool and format its result withtoModelOutput.
Result fields:
generateText: LLMAgent.asStream: LLMAgentStream
Additional fields:
generateText: LLMAgent additional result fields.asStream: LLMAgent additional result fields
Examples
LLMAgent
LLMAgent.ts
import { LLMAgent } from 'casai';
import type { LanguageModel } from 'ai';
// Answer the same customer question using the store returns policy.
export async function answerReturnQuestion(model: LanguageModel) {
const returnsAdvisor = LLMAgent({
model,
prompt: (
"Policy: Report damage within 30 days and include a photo. " +
"Replacement shipping is free.\n" +
"Question: My mug arrived cracked. What should I do?"
),
});
const result = await returnsAdvisor();
return {
output: result.output,
messageHistory: await result.messageHistory,
};
}
LLMAgent.asTool
LLMAgent.ts
import { LLMAgent, z } from 'casai';
import type { LanguageModel } from 'ai';
import { isStepCount } from 'ai';
// Answer the same customer question using the store returns policy.
export async function answerReturnQuestion(
model: LanguageModel,
orchestratorModel: LanguageModel,
) {
const returnsAdvisor = LLMAgent.asTool({
model,
// This tool answers the saved request; it accepts no new question.
description: (
"Explain how to return the damaged mug in this saved " +
"customer request."
),
inputSchema: z.object({}),
prompt: (
"Policy: Report damage within 30 days and include a photo. " +
"Replacement shipping is free.\n" +
"Question: My mug arrived cracked. What should I do?"
),
});
// Give this component to an AI agent as a tool.
const assistant = LLMAgent({
model: orchestratorModel,
tools: { returnsAdvisor },
stopWhen: isStepCount(3),
});
const answer = await assistant(
'Explain the return steps for the saved damaged-mug request.'
);
return {
text: answer.output,
toolResults: answer.steps.flatMap(step => step.toolResults),
};
}
- The .asTool modifier lets an AI agent or workflow call this component using declared input fields.
LLMAgent.asStream
LLMAgent.ts
import { LLMAgent } from 'casai';
import type { LanguageModel } from 'ai';
// Answer the same customer question using the store returns policy.
export async function answerReturnQuestion(model: LanguageModel) {
const returnsAdvisor = LLMAgent.asStream({
model,
prompt: (
"Policy: Report damage within 30 days and include a photo. " +
"Replacement shipping is free.\n" +
"Question: My mug arrived cracked. What should I do?"
),
});
const result = await returnsAdvisor();
for await (const part of result.fullStream) console.log(part);
return {
output: await result.output,
messageHistory: await result.messageHistory,
};
}
- The .asStream modifier returns the live AI SDK result so you can consume output as it arrives.
LLMAgent.withTemplate
LLMAgent.ts
import { LLMAgent, z } from 'casai';
import type { LanguageModel } from 'ai';
// Answer the same customer question using the store returns policy.
export async function answerReturnQuestion(model: LanguageModel) {
const policy = (
"Report damage within 30 days and include a photo. " +
"Replacement shipping is free."
);
const returnsAdvisor = LLMAgent.withTemplate({
model,
context: { policy },
inputSchema: z.object({ question: z.string() }),
prompt: `Policy: {{ policy }}
Question: {{ question }}
`,
});
const result = await returnsAdvisor(
{ question: "My mug arrived cracked. What should I do?" }
);
return {
output: result.output,
messageHistory: await result.messageHistory,
};
}
- The input text is a Cascada Template; the context object supplies its variables.
Decision
Evaluate the same content against one or more named questions using a decision model. Each question defines the kind of answer you need: a choice from categories, a boolean, a score or a box locating something in an image. This is useful for routing support requests, classifying content or checking several conditions in one call.
The content can be text, structured data or supported combinations of text and files. The result contains answers under their question names, together with native metadata. Supported question types and media depend on the selected model.
Status: Uses an experimental AI SDK operation.
Input: Content to evaluate and named questions to answer.
Returns: Typed answers and native decision metadata.
Configuration and supported forms
Main input: state
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool |
.withTemplate |
Ordinary, .asTool |
.withScript |
Ordinary, .asTool |
.withFunction |
Ordinary, .asTool |
.loadsText |
Ordinary, .asTool |
.loadsTemplate |
Ordinary, .asTool |
.loadsScript |
Ordinary, .asTool |
Default source: The text, JSON object or content parts to evaluate.
Source modifiers: .withText, .withTemplate, .loadsText, .loadsTemplate, .withScript, .withFunction, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Remaining AI SDK properties | runtimeContext, providerOptions, maxOutputTokens, reasoning, maxRetries, headers, telemetry, onStart, onEnd |
All supported forms |
| Required settings | model, questions, state |
All supported forms |
| Common Casai configuration | context, debug, description, inputSchema, tools, toolsContext |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Source preparation | filters, renderOptions |
All except default source, withFunction, loadsText |
| Source preparation | loader |
All except default source, withFunction |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior: Question definitions select classification, boolean, score or spatial answers. The actual question types and supported state parts belong to the selected model.
Tool execution output:
.asTool: The answers object.
Result fields: Decision
Examples
Decision.ts
import { Decision } from 'casai';
import type { Experimental_DecisionModel } from 'ai';
// Choose the team that should handle a damaged-mug request.
export async function routeSupportRequest(model: Experimental_DecisionModel) {
const routeRequest = Decision({
model,
questions: {
team: {
type: 'choice',
instructions: 'Choose the team best placed to resolve the request.',
criteria: {
returns: 'Damaged products and replacements',
billing: 'Charges and invoices',
delivery: 'Missing parcels',
},
},
},
});
const result = await routeRequest('My mug arrived cracked.');
return result.answers.team.choice;
}
Embedder
Represent text as a vector of numbers so your application can compare meaning rather than just matching words. Embeddings are useful for semantic search, finding related documents, clustering text and preparing content for retrieval before an AI model answers a question.
Pass one string to receive one embedding, or an array of strings to receive embeddings in the same order. Casai selects the corresponding AI SDK operation and preserves its result and metadata. Your application can store the vectors and compare them using a similarity function or a vector database.
Input: One text or an array of texts.
Returns: One embedding or a list of embeddings, plus native metadata.
Configuration and supported forms
Main input: input
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool |
.withTemplate |
Ordinary, .asTool |
.withScript |
Ordinary, .asTool |
.withFunction |
Ordinary, .asTool |
.loadsText |
Ordinary, .asTool |
.loadsTemplate |
Ordinary, .asTool |
.loadsScript |
Ordinary, .asTool |
Default source: The text or array of texts to embed.
Source modifiers: .withText, .withTemplate, .loadsText, .loadsTemplate, .withScript, .withFunction, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Remaining AI SDK properties | runtimeContext, providerOptions, maxRetries, headers, telemetry, experimental_telemetry, onStart, experimental_onStart, onEnd, dimensions, maxParallelCalls, experimental_onEnd |
All supported forms |
| Required settings | model, input |
All supported forms |
| Common Casai configuration | context, debug, description, inputSchema, tools, toolsContext |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Source preparation | filters, renderOptions |
All except default source, withFunction, loadsText |
| Source preparation | loader |
All except default source, withFunction |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior: A string returns one vector in embedding. An array, even with one item, returns embeddings in input order. Each result also includes the SDK’s usage and metadata.
Tool execution output:
.asTool: The vector or array of vectors.
Result fields: Embedder, EmbedderBatch
Examples
Embedder.ts
import { Embedder } from 'casai';
import type { EmbeddingModel } from 'ai';
// Create a search embedding for the same product description.
export async function embedProductDescription(model: EmbeddingModel) {
const embedProduct = Embedder({
model,
});
const result = await embedProduct(
'Trail mug. Insulated steel. Leakproof lid.'
);
return result.embedding;
}
Reranker
Improve search relevance by reordering candidate documents according to how well they answer a query. Reranking models evaluate the relationship between the query and each document. Use this after an initial search to choose the most useful passages for a reader or for an AI model to use in its answer.
Supply the query and candidate documents, with an optional topN limit. The result contains relevance scores, original indexes and documents in ranked order. Documents can be text or supported structured objects. Reranker ranks the candidates you supply; it does not search a data store itself.
Input: A query, candidate documents and optional result limit.
Returns: Native ranking entries with original indexes, documents and relevance scores.
Configuration and supported forms
Main input: query
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool |
.withTemplate |
Ordinary, .asTool |
.withScript |
Ordinary, .asTool |
.withFunction |
Ordinary, .asTool |
.loadsText |
Ordinary, .asTool |
.loadsTemplate |
Ordinary, .asTool |
.loadsScript |
Ordinary, .asTool |
Default source: The search text used to rank the candidate documents.
Source modifiers: .withText, .withTemplate, .loadsText, .loadsTemplate, .withScript, .withFunction, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Remaining AI SDK properties | runtimeContext, providerOptions, maxRetries, headers, telemetry, experimental_telemetry, onStart, experimental_onStart, onEnd, experimental_onEnd, topN |
All supported forms |
| Required settings | model, documents, query |
All supported forms |
| Common Casai configuration | context, debug, description, inputSchema, tools, toolsContext |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Source preparation | filters, renderOptions |
All except default source, withFunction, loadsText |
| Source preparation | loader |
All except default source, withFunction |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior: Native ranking entries with original indexes, documents and relevance scores.
Tool execution output:
.asTool: Therankingentries. Each carries the original candidate index, document and relevance score in{ originalIndex, document, score }.
Result fields: Reranker
Examples
Reranker.ts
import { Reranker } from 'casai';
import type { RerankingModel } from 'ai';
// Rank policy passages by relevance to a damaged-mug question.
export async function findRelevantPolicies(model: RerankingModel) {
const policies = [
'Send a photo of a damaged item within 30 days for a free replacement.',
'Update payment cards from account settings.',
'Follow your delivery using the tracking link.',
];
const findPolicy = Reranker({
model,
documents: policies,
});
const result = await findPolicy('How do I replace a damaged mug?');
return result.ranking;
}
ImageGenerator
Create images from a description using an image model. Use it for illustrations, product scenes, visual concepts or variations of an idea. Models that support image input can also use reference images, and supported editing models can use a mask to identify an area to change.
Request one image or several and choose supported settings such as size or aspect ratio. The result provides generated files as bytes or base64, together with native metadata. Available sizes, formats, reference-image behavior and editing capabilities depend on the selected model.
Input: Text or a native image prompt, with optional reference images, mask and count.
Returns: Generated images and the native generation metadata.
Configuration and supported forms
Main input: prompt
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool |
.withTemplate |
Ordinary, .asTool |
.withScript |
Ordinary, .asTool |
.withFunction |
Ordinary, .asTool |
.loadsText |
Ordinary, .asTool |
.loadsTemplate |
Ordinary, .asTool |
.loadsScript |
Ordinary, .asTool |
Default source: An image description, or an object with text, reference images and an optional mask.
Source modifiers: .withText, .withTemplate, .loadsText, .loadsTemplate, .withScript, .withFunction, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Remaining AI SDK properties | providerOptions, seed, maxRetries, headers, n, maxImagesPerCall, size, aspectRatio |
All supported forms |
| Required settings | model, prompt |
All supported forms |
| Component-specific and adapted behavior | images, mask |
All supported forms |
| Common Casai configuration | context, debug, description, inputSchema, tools, toolsContext |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Source preparation | filters, renderOptions |
All except default source, withFunction, loadsText |
| Source preparation | loader |
All except default source, withFunction |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior: Generated images and the native generation metadata.
Tool execution output:
.asTool: Files as { mediaType, base64 }[]. Native file-content projection delivers images where the receiving adapter/model supports them. Native errors and adapter limitations remain native; Casai adds no capability or repair layer. Use toModelOutput to customize what the model sees.
Result fields: ImageGenerator
Examples
ImageGenerator.ts
import { ImageGenerator } from 'casai';
import type { ImageModel } from 'ai';
// Create a product photo of a Trail mug in a mountain scene.
export async function createProductPhoto(model: ImageModel) {
const productScene = ImageGenerator({
model,
});
const result = await productScene(
(
"Place a Trail mug on a picnic table beside a mountain " +
"lake. Keep the mug shape and markings unchanged."
)
);
return result.images.map(image => ({
bytes: image.uint8Array,
mediaType: image.mediaType,
}));
}
Transcriber
Transcribe a recording in a format your provider accepts without installing node-av. Pass encoded bytes or a URL object for AI SDK file transcription. For a raw-input model, set inputAudioFormat and pass a WAV file, AudioBuffer, headerless samples or a raw stream. Casai converts WAV and described PCM in the browser or Node.js. Ordinary calls return a completed transcript. Select .asStream for live transcript events.
Use .loadsAudio in Node.js when FFmpeg should open a recording, extract a track from video or convert its format. This requires node-av. Configure fileAudioTarget for file transcription or supply inputAudioFormat for raw audio. Use .withAudio to reset inherited preparation.
Status:
.asStream: Uses an experimental AI SDK operation.
Input:
Ordinary,.asTool: Pass an encoded file, bytes, base64 or a native URL for file transcription. For a raw-input model, Casai reads the source format from a WAV or AudioBuffer. For headerless sample arrays, supply the sample rate and channel count. A fresh raw stream can go straight to a matching model format. Use .loadsAudio to decode a path, URL or upload with FFmpeg..asStream: Supply a WAV, AudioBuffer, headerless samples or a fresh raw stream and select the model target with inputAudioFormat. Use .loadsAudio to decode a path, URL or upload with FFmpeg.
Returns:
Ordinary,.asTool: Completed transcript text, segments, language, duration and native metadata..asStream: Native transcription events and final transcript promises.
.asStream: Produce transcript updates using a transcription model with streaming support. Use this for live captions, voice input or transcript updates from a recording. Supply raw audio bytes or a fresh stream with inputAudioFormat. Use .loadsAudio.asStream to prepare a path/URL, encoded bytes or a byte stream.
The result exposes transcript events and promises for the final transcript and metadata. Consume fullStream before awaiting the final values if you need the events. Supported raw-audio formats depend on the provider; encoded file bytes must be decoded before they can be used as raw samples.
Configuration and supported forms
Main input: audio
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool, .asStream |
.withScript |
Ordinary, .asTool, .asStream |
.withFunction |
Ordinary, .asTool, .asStream |
.loadsAudio |
Ordinary, .asTool, .asStream |
.loadsScript |
Ordinary, .asTool, .asStream |
Default source: An encoded recording, base64 or an SDK URL for file transcription. With inputAudioFormat, pass a WAV, AudioBuffer, described samples or raw chunks.
Source modifiers: .withAudio, .loadsAudio, .withScript, .withFunction, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Remaining AI SDK properties | providerOptions, headers, telemetry |
All supported forms |
| Required settings | model, audio |
All supported forms |
| Component-specific and adapted behavior | inputAudioFormat |
All supported forms |
| Source preparation | sourceFormat |
All supported forms |
| Common Casai configuration | context, debug, description, inputSchema, tools, toolsContext |
All supported forms |
| Remaining AI SDK properties | maxRetries |
Ordinary, .asTool |
| Remaining AI SDK properties | download |
All except .asStream; Ordinary + loadsAudio; .asTool + loadsAudio |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Remaining AI SDK properties | includeRawChunks |
.asStream |
| Source preparation | filters, renderOptions, loader |
withScript, loadsScript |
| Source preparation | mediaSettings |
loadsAudio |
| Source preparation | fileAudioTarget |
loadsAudio + Ordinary, .asTool |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
transcribe (All except .asStream; Ordinary + loadsAudio; .asTool + loadsAudio): Encoded audio or a native URL without inputAudioFormat. transcribe request
experimental_streamTranscribe (Ordinary, .asTool): Raw audio with inputAudioFormat, including prepared .loadsAudio input. experimental_streamTranscribe request
experimental_streamTranscribe (.asStream): Every .asStream call; the model must support streaming. experimental_streamTranscribe request
transcribe (loadsAudio + Ordinary, .asTool): Encoded audio or a native URL without inputAudioFormat. transcribe request
Results
Behavior:
-
Ordinary,.asTool: Returns the completed transcript and metadata. Encoded-file transcription returns the native transcribe result; raw-audio transcription awaits the final fields from native streaming. The input and inputAudioFormat select the operation, which the model must support. A supplied native URL plus inputAudioFormat is rejected before dispatch; .loadsAudio can prepare a URL into raw audio and remains valid with that target. -
.asStream:Use
fullStreamfor transcript deltas, partial transcripts and final events. If you also need final fields such astext, consume the stream before accessing those promises. Reading a final-result promise first lets the SDK consume the stream.A transport or iteration failure can deliver a prefix and then reject the pending results. An
errorevent followed by a valid finish can still yield a final transcript. All views use the same SDK execution.
Tool execution output:
.asTool: Return text, segments, language and durationInSeconds; the model receives transcript text. Plain public audio arguments are URLs parsed to native URL values for the SDK downloader. .loadsAudio.asTool requires configured audio and model arguments cannot replace it. Configured media stays private. Explicit Function/Script workflows handle dynamic native resources; source preparers retain application-defined payloads and native audio results.
Result fields:
Ordinary,.asTool: Transcriber.asStream: TranscriberStream
Examples
Transcriber
Transcriber.ts
import { Transcriber } from 'casai';
import type { TranscriptionModel } from 'ai';
// Transcribe the same delivery note.
// Supply encoded file bytes, raw samples or a media location.
export async function transcribeDeliveryNote(
model: TranscriptionModel,
recording: Uint8Array,
) {
const transcribeNote = Transcriber({
model,
});
const result = await transcribeNote(recording);
return result.text;
}
Transcriber.loadsAudio
Transcriber.ts
import { Transcriber } from 'casai';
import type { TranscriptionModel } from 'ai';
// Transcribe the same delivery note.
// Supply encoded file bytes, raw samples or a media location.
export async function transcribeDeliveryNote(
model: TranscriptionModel,
recordingUrl: URL,
) {
// Supply an application-authorized recordingUrl, including trusted
// redirects and playlist resources.
const transcribeNote = Transcriber.loadsAudio({
model,
// Requires a model with streaming support for 24 kHz mono PCM16.
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
// Install node-av. FFmpeg detects the format
// and selects its best audio stream.
mediaSettings: {},
});
const result = await transcribeNote(recordingUrl);
return result.text;
}
- Requires node-av in Node.js. FFmpeg opens a path, URL, encoded bytes or byte stream, selects an audio track and copies or converts it to the requested format.
SpeechGenerator
Turn written text into spoken audio using a speech model. Use it for narration, spoken notifications, accessibility features or a voice response in an application. Choose a voice and audio format supported by the selected provider.
Ordinary calls return a generated audio file with bytes, base64 data and metadata. Select .asStream when playback should begin before generation finishes. Both forms accept a complete text string or text arriving gradually, such as a language model response. Incremental text requires a model with streaming support, even when the call returns a completed audio file.
Status:
.asStream: Uses an experimental AI SDK operation.
Input:
Ordinary,.asTool: Text as a string, iterable or stream, and optional voice..asStream: A text string, iterable or stream of text deltas/parts; optional voice.
Returns:
Ordinary,.asTool: A generated audio file and native metadata; collected streaming speech also includes audioFormat and usage..asStream: Live audio events and final native metadata.
.asStream: Generate speech in chunks so an application can begin playback before all the audio is ready. Supply a complete text string or feed text incrementally, for example from a language model response. The selected speech model must support streaming.
Consume audioStream for audio bytes, or fullStream for audio and other events, then await final metadata. Your application handles playback or delivery. Choose a supported voice and, optionally, an outputFormat object such as { type: "audio/mpeg" }.
Configuration and supported forms
Main input: text
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool, .asStream |
.withTemplate |
Ordinary, .asTool, .asStream |
.withScript |
Ordinary, .asTool, .asStream |
.withFunction |
Ordinary, .asTool, .asStream |
.loadsText |
Ordinary, .asTool, .asStream |
.loadsTemplate |
Ordinary, .asTool, .asStream |
.loadsScript |
Ordinary, .asTool, .asStream |
Default source: Text to read aloud, supplied as a string, iterable or stream.
Source modifiers: .withText, .withTemplate, .loadsText, .loadsTemplate, .withScript, .withFunction, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Remaining AI SDK properties | providerOptions, headers, instructions, onError, voice, outputFormat, speed, language |
All supported forms |
| Required settings | model, text |
All supported forms |
| Common Casai configuration | context, debug, description, inputSchema, tools, toolsContext |
All supported forms |
| Remaining AI SDK properties | maxRetries, telemetry |
Ordinary, .asTool |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Remaining AI SDK properties | includeRawChunks |
.asStream |
| Source preparation | filters, renderOptions |
All except default source, withFunction, loadsText |
| Source preparation | loader |
All except default source, withFunction |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
generateSpeech (Ordinary, .asTool): String text and absent/string outputFormat. maxRetries and telemetry belong to this operation. generateSpeech request
experimental_streamSpeech (Ordinary, .asTool): Object outputFormat, or native non-string text with absent/object outputFormat. String outputFormat with non-string text is rejected; maxRetries and telemetry are excluded. experimental_streamSpeech request
experimental_streamSpeech (.asStream): Every .asStream call; outputFormat is an optional native object. experimental_streamSpeech request
Results
Behavior:
Ordinary,.asTool: Both completed paths use SpeechResult with optional audioFormat and usage. Native complete results remain unchanged; collection adds the actual emitted format and resolved streaming usage. Changing request format does not change the result envelope. Collection rejects if the audio stream fails or nonempty chunks have incompatible formats..asStream: Returns native audioStream, fullStream and final metadata promises. Choose one stream view and consume it before awaiting final metadata; these views share one execution. .asStream cannot be combined with .asTool.
Tool execution output:
.asTool: A file as { mediaType, base64 }, with actual audioFormat for collected streaming. The default uses native file content with the SDK media information; the receiving adapter/model owns format acceptance. Optional toModelOutput can package known PCM as WAV or choose another representation. Missing raw metadata adds no Casai requirement or guessed conversion. No canned confirmation.
Result fields:
Ordinary,.asTool: SpeechGenerator.asStream: SpeechGeneratorStream
Examples
SpeechGenerator
SpeechGenerator.ts
import { SpeechGenerator } from 'casai';
import type { SpeechModel } from 'ai';
// Turn a delivery update into spoken audio.
export async function speakDeliveryUpdate(model: SpeechModel) {
const speakUpdate = SpeechGenerator({
model,
});
const result = await speakUpdate(
'Hello Ada. Your Northstar order is due Friday.'
);
return {
bytes: result.audio.uint8Array,
mediaType: result.audio.mediaType,
};
}
SpeechGenerator.asStream
SpeechGenerator.ts
import { SpeechGenerator } from 'casai';
import type { SpeechModel } from 'ai';
// Turn a delivery update into spoken audio.
export async function speakDeliveryUpdate(model: SpeechModel) {
const speakUpdate = SpeechGenerator.asStream({
model,
});
const result = await speakUpdate(
'Hello Ada. Your Northstar order is due Friday.'
);
// Consume the stream once before reading final values.
for await (const part of result.fullStream) {
console.log(part);
}
return await result.usage;
}
- Returns speech in audio chunks from a supporting model.
Translator
Translate spoken content into audio and text in another language using a speech translation model. Ordinary calls and tools collect one AI SDK operation into audio bytes, final source text, translated text and metadata. Select .asStream for incremental events.
Supply a WAV, AudioBuffer, headerless PCM or raw stream with the model target inputAudioFormat and targetLanguage. Casai prepares WAV and described PCM without node-av. For other encoded recordings or video, use .loadsAudio in Node.js with node-av installed. FFmpeg prepares the track in the requested inputAudioFormat. Use .withAudio to reset inherited preparation. For written-text translation, use LLMAgent with translation instructions.
Status: Uses an experimental AI SDK operation.
Input:
Ordinary,.asTool: Supply a WAV, AudioBuffer, headerless samples or a finite raw stream along with the model target format and target language. Use .loadsAudio to decode a path, URL or upload with FFmpeg..asStream: A WAV, AudioBuffer, headerless samples or a fresh raw stream, its format and target language; .loadsAudio prepares paths/URLs, encoded bytes and byte streams.
Returns:
Ordinary,.asTool: Completed audio bytes, final source/translated text and native final metadata..asStream: Live translated audio/text events and native final promises.
.asStream: Translate speech into target-language audio and text as raw audio arrives. Use this when an application needs translation updates before a recording ends. Supply raw bytes or a fresh stream, its input format and the target language. Use .loadsAudio.asStream to prepare a path/URL, encoded bytes or a byte stream.
Consume fullStream to receive translated audio and text events, then read the final source text, translated text and metadata. The model must support speech translation. Supported languages and formats depend on the provider; written-text translation uses LLMAgent.
Configuration and supported forms
Main input: audio
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool, .asStream |
.withScript |
Ordinary, .asTool, .asStream |
.withFunction |
Ordinary, .asTool, .asStream |
.loadsAudio |
Ordinary, .asTool, .asStream |
.loadsScript |
Ordinary, .asTool, .asStream |
Default source: A WAV file, AudioBuffer, headerless samples or a finite raw stream to translate.
Source modifiers: .withAudio, .loadsAudio, .withScript, .withFunction, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Remaining AI SDK properties | providerOptions, headers, outputAudioFormat, sourceLanguage |
All supported forms |
| Required settings | model, inputAudioFormat, targetLanguage, audio |
All supported forms |
| Source preparation | sourceFormat |
All supported forms |
| Common Casai configuration | context, debug, description, inputSchema, tools, toolsContext |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Remaining AI SDK properties | includeRawChunks |
.asStream |
| Source preparation | filters, renderOptions, loader |
withScript, loadsScript |
| Source preparation | mediaSettings |
loadsAudio |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior:
-
Ordinary,.asTool:Returns
audioas a Uint8Array together with final source text, translated text and native metadata. Use the provider’s actual output format to interpret the bytes. A provider may return empty audio for text-only output or empty translated text for audio-only output.The call waits for audio collection. A stream failure rejects the call even if final-text promises have resolved. A nonfatal
errorevent followed by a successful finish can still yield a completed result. UseTranslator.asStreamto inspect individual events infullStream. -
.asStream: Returns native fullStream and final metadata promises. Consume fullStream before awaiting final values if you need the audio and text events; reading a final promise first can consume the stream. .asStream cannot be combined with .asTool.
Tool execution output:
.asTool: Completed source/translated text, base64 audio and optional duration from one execution. The default model output contains only translationText; audio remains in the execution result and is available to optional toModelOutput. Ten seconds of 24 kHz mono PCM16 is 640,000 base64 characters. Audio-only output can give empty model text without a new Casai error or confirmation; supply a formatter when that needs useful media content.
Result fields:
Ordinary,.asTool: Translator.asStream: TranslatorStream
Examples
Translator
Translator.ts
import { Translator } from 'casai';
// Translate the same spoken delivery note into French.
// This model accepts 24 kHz mono PCM16.
export async function translateDeliveryNote(
model: Parameters<
typeof import('ai').experimental_streamTranslate
>[0]['model'],
pcm24k: Uint8Array,
) {
// Open a fresh stream over 24 kHz mono PCM16 little-endian bytes.
const openRecording = () => {
let offset = 0;
return new ReadableStream<Uint8Array>({
pull(controller) {
if (offset === pcm24k.byteLength) return controller.close();
const end = Math.min(offset + 9600, pcm24k.byteLength);
controller.enqueue(pcm24k.subarray(offset, end));
offset = end;
},
}, { highWaterMark: 0 });
};
const translateNote = Translator({
model,
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
targetLanguage: 'fr',
});
const result = await translateNote(openRecording());
// The completed result contains audio bytes and final text.
return {
audio: result.audio,
sourceText: result.sourceText,
translationText: result.translationText,
};
}
Translator.asStream
Translator.ts
import { Translator } from 'casai';
// Translate the same spoken delivery note into French.
// This model accepts 24 kHz mono PCM16.
export async function translateDeliveryNote(
model: Parameters<
typeof import('ai').experimental_streamTranslate
>[0]['model'],
pcm24k: Uint8Array,
) {
// Open a fresh stream over 24 kHz mono PCM16 little-endian bytes.
const openRecording = () => {
let offset = 0;
return new ReadableStream<Uint8Array>({
pull(controller) {
if (offset === pcm24k.byteLength) return controller.close();
const end = Math.min(offset + 9600, pcm24k.byteLength);
controller.enqueue(pcm24k.subarray(offset, end));
offset = end;
},
}, { highWaterMark: 0 });
};
const translateNote = Translator.asStream({
model,
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
targetLanguage: 'fr',
});
const result = await translateNote(openRecording());
// Consume the stream once before reading final values.
for await (const part of result.fullStream) {
console.log(part);
}
return await result.translationText;
}
- The .asStream modifier returns the live AI SDK result so you can consume output as it arrives.
VideoGenerator
Generate video clips from text or an image prompt, with provider-supported reference media and generation settings. Configure a reusable component, prepare its prompt with a template, script or function, and call it from JavaScript or Cascada Script.
Ordinary calls return the native completed video result. The AI SDK owns asynchronous provider jobs, polling, webhook completion, retries and downloads. Each call is independent; configuration contains no job state. This component has no .asStream modifier. Tool forms return file payloads; the calling model must support the video file type or the application must supply a suitable toModelOutput mapping.
Status:
Work in progress: VideoGenerator component and native video generation integration.
Uses an experimental AI SDK operation.
Input: A text prompt or native image-and-text prompt, with supported reference media and generation settings.
Returns: The native completed video files, warnings, responses and provider metadata.
Configuration and supported forms
Main input: prompt
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, .asTool |
.withTemplate |
Ordinary, .asTool |
.withScript |
Ordinary, .asTool |
.withFunction |
Ordinary, .asTool |
.loadsText |
Ordinary, .asTool |
.loadsTemplate |
Ordinary, .asTool |
.loadsScript |
Ordinary, .asTool |
Default source: A video description, or a native object containing an image and optional text.
Source modifiers: .withText, .withTemplate, .withScript, .withFunction, .loadsText, .loadsTemplate, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Common Casai configuration | inputSchema, context, debug, description, tools, toolsContext |
All supported forms |
| Remaining AI SDK properties | providerOptions, seed, maxRetries, headers, n, aspectRatio, download, maxVideosPerCall, resolution, duration, fps, frameImages, inputReferences, generateAudio, poll, webhook |
All supported forms |
| Required settings | prompt, model |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Tool configuration | toolContextSchema, onInputAvailable, onInputStart, onInputDelta, needsApproval, title, deferLoading, metadata, toModelOutput, strict, inputExamples |
.asTool |
| Source preparation | filters, renderOptions |
All except default source, withFunction, loadsText |
| Source preparation | loader |
All except default source, withFunction |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
bindToolContext |
.asTool |
execute |
.asTool |
Results
Behavior: The SDK owns direct generation or asynchronous start/status completion, including supported polling and webhook handling. The callable component stores no job state. Returned files expose bytes, base64 and mediaType. Provider support determines media and generation capabilities; there is no incremental video result or .asStream modifier.
Tool execution output:
.asTool: Files as { mediaType, base64 }[]. The default model output uses native file content parts. Receiving video support depends on the adapter/model; Casai preserves native errors and limitations without automatic repair. Use toModelOutput to deliberately choose an application-specific representation.
Result fields: VideoGenerator
Examples
VideoGenerator.ts
import { VideoGenerator } from 'casai';
import type { VideoModel } from 'ai';
// Generate a short product video using the selected provider model.
export async function createProductVideo(model: VideoModel) {
const productClip = VideoGenerator({
model,
});
const result = await productClip(
(
"A slow camera move around a Trail mug beside a mountain " +
"lake at sunrise."
)
);
return result.videos.map(video => ({
bytes: video.uint8Array,
mediaType: video.mediaType,
}));
}
- Work in progress: VideoGenerator component and native video generation integration.
VoiceAgentClient
Create independent browser voice sessions from a stateless reusable component. Pass the returned handle between browser Cascada scripts or application callbacks. Each call returns a disconnected session; connect explicitly to start the conversation. Use native microphone, playback, text, audio and tool controls, and subscribe to snapshots to update any framework or plain JavaScript UI.
Import from casai/client. Your application routes pair with VoiceAgentBackend for session setup and private tools, keeping provider API keys and tool executors on the server. Native token, WebRTC and relay options retain their provider and browser restrictions. Share explicitly public typed preferences when useful; do not pass backend configuration to the browser.
Status:
Work in progress: VoiceAgentClient browser entry, session factory and state subscriptions.
Uses the experimental AI SDK realtime session interface.
Input: Configured browser realtime model and native API endpoint settings; no source argument.
Returns: An independent disconnected realtime session with native controls and observable state.
Configuration and supported forms
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary |
| Group | Properties | Available in |
|---|---|---|
| Required settings | model, api |
All supported forms |
| Remaining AI SDK properties | sessionConfig, sampleRate, maxEvents, startupTimeoutMs, closeTimeoutMs, rtcDisconnectTimeoutMs, maxPlaybackBufferSeconds, onToolCall, onEvent, onError |
All supported forms |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
Results
Behavior: Each call returns independent state in a native session handle; the reusable component stores no current session. Pass the handle between browser Cascada scripts or callbacks. Connect explicitly and observe connected status before readiness-dependent commands. getSnapshot and subscribe provide optional framework-independent observation. Native controls, audio and capability errors retain SDK behavior. The host owns close/dispose and unsubscribe, including cleanup after script failure.
Result fields: VoiceAgentClient
Examples
VoiceAgentClient.ts
import { VoiceAgentClient } from 'casai/client';
import type { Experimental_RealtimeModel } from 'ai';
export async function prepareVoiceSupportClient(
model: Experimental_RealtimeModel,
) {
const voiceSupport = VoiceAgentClient({
model,
// Your route authenticates the user and calls VoiceAgentBackend.
api: { token: '/api/voice/setup' },
sessionConfig: { voice: 'alloy' },
});
const session = await voiceSupport();
// Pass this handle to browser Cascada scripts or application callbacks.
// Connect explicitly, then observe status === 'connected' before sending.
// Optional UI adapters use session.subscribe and session.getSnapshot.
// The owner gracefully closes and disposes the handle when finished.
return session;
}
- Work in progress: VoiceAgentClient browser entry, session factory and state subscriptions.
VoiceAgentBackend
Set up the server side of a realtime voice conversation with an AI model and execute its tool calls. Configure the model, instructions and tools, then use the setup method supported by the provider: create a short-lived client secret, prepare session configuration or answer a browser WebRTC offer. The browser handles audio capture and playback; your application owns network connections and the conversation lifecycle.
When the session supports tools, executeTool validates and runs a registered tool with the incoming call information and trusted server context. Those tools can access private application data and server services.
Keep provider API keys and tool executors on the server. For direct provider connections, the browser receives a short-lived session credential or a WebRTC setup response. Your application server authenticates users and authorizes session creation and tool calls. A session credential authenticates the provider connection; it does not replace these application access checks.
Status: Uses an experimental AI SDK operation.
Input:
- All except
doCreateWebRTCSession: Server-owned instructions, model, session preferences and optional tools. doCreateWebRTCSession: A browser SDP offer, server-owned instructions, session preferences and optional tools.
Returns:
doCreateClientSecret: Client-secret information plus prepared tool definitions.prepareSessionConfig: Prepared native session configuration, including instructions and tool definitions.doCreateWebRTCSession: The native WebRTC session result, including the SDP answer.
Configuration and supported forms
Main input: instructions
| Source | Supported delivery / operation |
|---|---|
| Default | Ordinary, Ordinary / prepareSessionConfig, Ordinary / createWebRTCSession |
.withTemplate |
Ordinary, Ordinary / prepareSessionConfig, Ordinary / createWebRTCSession |
.withScript |
Ordinary, Ordinary / prepareSessionConfig, Ordinary / createWebRTCSession |
.withFunction |
Ordinary, Ordinary / prepareSessionConfig, Ordinary / createWebRTCSession |
.loadsText |
Ordinary, Ordinary / prepareSessionConfig, Ordinary / createWebRTCSession |
.loadsTemplate |
Ordinary, Ordinary / prepareSessionConfig, Ordinary / createWebRTCSession |
.loadsScript |
Ordinary, Ordinary / prepareSessionConfig, Ordinary / createWebRTCSession |
Default source: Instructions defining how the voice assistant should respond.
Source modifiers: .withText, .withTemplate, .loadsText, .loadsTemplate, .withScript, .withFunction, .loadsScript
| Group | Properties | Available in |
|---|---|---|
| Remaining AI SDK properties | providerOptions, inputAudioFormat, voice, outputModalities, inputAudioTranscription, outputAudioTranscription, outputAudioFormat, turnDetection, expiresAfterSeconds |
All supported forms |
| Required settings | model, instructions |
All supported forms |
| Common Casai configuration | context, debug, description, inputSchema, tools, toolsContext |
All supported forms |
| Invocation reference | abortSignal |
All supported forms |
| Source preparation | filters, renderOptions |
All except default source, withFunction, loadsText |
| Source preparation | loader |
All except default source, withFunction |
| Call or method | Available in |
|---|---|
call |
All supported forms |
run |
All supported forms |
config |
All supported forms |
prepareSessionConfig |
All supported forms |
createWebRTCSession |
All supported forms |
executeTool |
All supported forms |
Results
Behavior:
doCreateClientSecret: Ordinary calls and run return a short-lived client secret and prepared tool definitions where the model supports this setup. Pass that setup data to the browser for its provider connection; the provider API key stays on the server. Token, WebRTC and Live capabilities differ by provider. The application server authenticates users, authorizes session creation and tool calls, and supplies matching trusted context; the application owns transport.prepareSessionConfig: Returns session configuration without opening a provider session. Empty tool definitions are omitted. The application supplies it to the supported session transport.doCreateWebRTCSession: Pass the returned SDP answer to the browser peer connection. Provider API credentials stay on the server. The provider owns the result fields and capability errors; the application server authenticates and authorizes the setup request, and the application owns transport.
Result fields:
doCreateClientSecret: VoiceAgentBackendprepareSessionConfig: VoiceSessionConfigdoCreateWebRTCSession: VoiceWebRTC
Examples
VoiceAgentBackend.ts
import { VoiceAgentBackend } from 'casai';
import type { Experimental_RealtimeModel } from 'ai';
// Prepare a browser voice assistant with a realtime model
// supporting the selected session method.
export async function prepareVoiceSupportSession(
model: Experimental_RealtimeModel,
) {
const voiceSupport = VoiceAgentBackend({
model,
instructions: (
"Help Northstar customers in English. Keep replies short " +
"and ask one question at a time."
),
});
const session = await voiceSupport();
return session;
}
Source modifiers
The main input is the component property named in its configuration section, such as prompt, text or audio. The component tables show supported combinations; source preparation does not change output delivery.
.withAudio
Behavior:
- Config: The receiving component uses supplied audio directly, replacing inherited media or source preparation. This explicit selection replaces an inherited source mode. The source value and any required loader may be supplied by the completed component.
- Transcriber (
Ordinary,.asTool): An encoded recording, base64 or an SDK URL for file transcription. With inputAudioFormat, pass a WAV, AudioBuffer, described samples or raw chunks. - Transcriber (
.asStream): A WAV file, AudioBuffer, headerless samples or a fresh raw stream to transcribe. - Translator (
Ordinary,.asTool): A WAV file, AudioBuffer, headerless samples or a finite raw stream to translate. - Translator (
.asStream): A WAV file, AudioBuffer, headerless samples or a fresh raw stream to translate.
.withText
Behavior:
- Config: The receiving component uses its primary input directly. This explicit selection replaces an inherited source mode. The source value and any required loader may be supplied by the completed component.
- LLMAgent: The text or messages to send to the model.
- Decision: The text, JSON object or content parts to evaluate.
- Embedder: The text or array of texts to embed.
- Reranker: The search text used to rank the candidate documents.
- ImageGenerator: An image description, or an object with text, reference images and an optional mask.
- SpeechGenerator (
Ordinary,.asTool): Text to read aloud, supplied as a string, iterable or stream. - SpeechGenerator (
.asStream): The text to read aloud, supplied as a string, iterable or stream. - VideoGenerator: A video description, or a native object containing an image and optional text.
- VoiceAgentBackend: Instructions defining how the voice assistant should respond.
.withTemplate
Behavior:
- Config: The receiving component renders its primary input as a Cascada Template, using variables from context. This explicit selection replaces an inherited source mode. The source value and any required loader may be supplied by the completed component.
- Template; Embedder; Reranker; SpeechGenerator; VoiceAgentBackend: The
main inputvalue contains Cascada Template text. Casai fills in the template variables from thecontextobject. For example,Hello {{ name }}withcontext: { name: "Ada" }producesHello Ada. - LLMAgent: The
main inputvalue contains Cascada Template text. Casai fills in the template variables from thecontextobject. For example,Hello {{ name }}withcontext: { name: "Ada" }producesHello Ada. For a message object or array of messages, templates are rendered in text content. Images, files and other message parts are passed through unchanged. - Decision: The
main inputvalue contains Cascada Template text. Casai fills in the template variables from thecontextobject. For example,Hello {{ name }}withcontext: { name: "Ada" }producesHello Ada. In an array of parts, only objects with type "text" contain templates. File and JSON parts are passed through unchanged. - ImageGenerator: The
main inputvalue contains Cascada Template text. Casai fills in the template variables from thecontextobject. For example,Hello {{ name }}withcontext: { name: "Ada" }producesHello Ada. For an object prompt, the text field contains the template. Images and the mask are passed through unchanged. - VideoGenerator: The
main inputvalue contains Cascada Template text. Casai fills in the template variables from thecontextobject. For example,Hello {{ name }}withcontext: { name: "Ada" }producesHello Ada. Render only the text field of an object prompt; image data stays unchanged.
.withScript
Behavior:
- Config: The receiving component runs its primary input as a Cascada Script, using variables from context. This explicit selection replaces an inherited source mode. The source value and any required loader may be supplied by the completed component.
- Script: The
main inputvalue is Cascada Script code. Fields of thecontextobject are available as variables. The script’s return value is the component’s result. - All except Config; Script: The
main inputvalue is Cascada Script code. Fields of thecontextobject are available as variables. The script’s return value suppliesmain input.
.withFunction
Behavior:
- Config: The receiving component calls the function supplied as its primary input, passing context. The function may be asynchronous. This explicit selection replaces an inherited source mode. The source value and any required loader may be supplied by the completed component.
- All except Config: The
main inputvalue is a JavaScript function. Casai passes it thecontextobject and uses its return value asmain input. The function may be asynchronous. It runs once per invocation. Where the operation accepts streamed input, it can return a fresh stream, directly or through a promise; Casai does not collect that input before dispatch. Output delivery is selected separately with .asStream. Other operations retain their native input requirements.
.loadsText
Behavior:
- Config: The receiving component loads its primary input from a text file using loader. This explicit selection replaces an inherited source mode. The source value and any required loader may be supplied by the completed component.
- LLMAgent: A file containing the prompt text to send to the model. The
main inputvalue is a file name passed to the configuredloader. - Decision: A file containing the text to evaluate against the configured questions. The
main inputvalue is a file name passed to the configuredloader. - Embedder: A file containing the text to embed as one vector. The
main inputvalue is a file name passed to the configuredloader. - Reranker: A file containing the search query used to rank the candidate documents. The
main inputvalue is a file name passed to the configuredloader. - ImageGenerator: A file containing the description of the image to generate. The
main inputvalue is a file name passed to the configuredloader. - SpeechGenerator: A file containing the text to read aloud. The
main inputvalue is a file name passed to the configuredloader. - VideoGenerator: A file containing the description of the video to generate. The
main inputvalue is a file name passed to the configuredloader. - VoiceAgentBackend: A file containing instructions for the voice assistant. The
main inputvalue is a file name passed to the configuredloader.
.loadsTemplate
Behavior:
- Config: The receiving component loads a Cascada Template using loader and renders it using context. This explicit selection replaces an inherited source mode. The source value and any required loader may be supplied by the completed component.
- All except Config: The
main inputvalue is a file name passed to the configuredloader. The file contains Cascada Template text. Casai fills in the template variables from thecontextobject. For example,Hello {{ name }}withcontext: { name: "Ada" }producesHello Ada.
.loadsScript
Behavior:
- Config: The receiving component loads a Cascada Script using loader and runs it using context. This explicit selection replaces an inherited source mode. The source value and any required loader may be supplied by the completed component.
- Script: The
main inputvalue is a file name passed to the configuredloader. Casai runs the loaded Cascada Script with fields ofcontextavailable as variables. The script’s return value is the component’s result. - All except Config; Script: The
main inputvalue is a file name passed to the configuredloader. Casai runs the loaded Cascada Script with fields ofcontextavailable as variables. The script’s return value suppliesmain input.
.loadsAudio
Behavior:
- Config: FFmpeg opens a path, URL, File, Blob, supplied bytes or byte stream. It detects the recording format, selects an audio track and prepares it for the model. Requires node-av; no loader setting is used. This explicit selection replaces an inherited source mode. The media location and input settings may be supplied by the completed component.
- All except Config: The audio value supplies a local/remote media reference or encoded bytes/byte stream, including video with an audio track. FFmpeg/node-av opens it and prepares the selected audio. mediaSettings describes the source; inputAudioFormat describes the raw model target. Encoded-file transcription instead requires a configured file target describing accepted formats and limits. No loader configuration is needed. Relative paths resolve against the process working directory. Each path/URL call opens afresh; finite bytes can be reused, while supplied streams remain single-use. Native preparation and SDK dispatch share one identity check; reusing a handed-off ReadableStream raises ValidationError before another read. The .asTool form requires configured audio, including inheritance, and model arguments cannot replace that source. Declared context fields remain data. Trusted application calls retain explicit source overrides; dynamic native resources use an explicit Function/Script workflow. Native byte inputs deny nested protocol opens by default, with an explicit trusted mediaSettings.options.protocol_whitelist override.
Shared property reference
Properties are listed once by name. Each component links to the properties it supports. Conditional entries specify the component, source or delivery where a rule applies. Construction means factory configuration; ordinary means positional calls; run means named .run() input.
The following defaults apply unless a property states otherwise:
Required: Optional.
Inheritance: Constructor child values replace inherited values; omitted settings inherit. Supported invocation overrides apply only to that invocation.
Overrides: Supported through .run(); see the property-specific merge/clearing rule.
inputSchema
Description: Validates public application input after combining defaults and caller arguments.
Type: Zod 4 Classic/Mini, SDK Schema, or Standard Schema for an object
Required: Required for .asTool; its root must declare every public input field. Optional on ordinary components.
Accepted by:
- Config; Template; Script; Function; LLMAgent; Decision; Embedder; Reranker; ImageGenerator; Transcriber; SpeechGenerator; Translator; VideoGenerator; VoiceAgentBackend: construction
Overrides:
- All except Context: Fixed at construction; derive a component to replace it.
- Context: These are related component settings or injected context values. See the receiving component for its invocation rules.
Notes: Callers and defaults use schema input types; implementations use parsed output types. Reject undeclared tool arguments before parsing. Dynamic dictionaries belong inside a declared field. Zod 3 is not supported here.
filters
Description: Named functions available as Cascada filters in authored templates and scripts.
Type: Record<string, (input: any, ...args: any[]) => any> | undefined
Default: Cascada built-ins only.
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Inheritance: Shallow merge by name; child entries replace inherited entries.
Notes: Creation-time rendering settings. This does not register model tools.
renderOptions
Description: Configures Cascada rendering and source caching.
Type: ConfigureOptions | undefined
Values: An object of Cascada rendering options, such as autoescape, trimBlocks and lstripBlocks. Expand the rendering options below for individual fields.
Default: Standalone Template autoescape is false; AI source preparers always disable HTML escaping.
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Notes: Creation-time only. replayAsyncIterables defaults to sharing iterations; use fresh sources or disable replay for native single-use behavior.
Fields: renderOptions fields
loader
Description: Reads text, templates or scripts by name, for example from a file or URL.
Type: Loader function | object with load(name) | ordered loader list
Required: Required in a completed component using .loadsText, .loadsTemplate or .loadsScript. .loadsAudio uses native media loading instead.
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Inheritance: Child loaders run before parent loaders. undefined preserves the chain. raceParent and overrideParent explicitly change composition.
Notes: An array tries loaders in order. raceLoaders tries loaders concurrently. FileSystemLoader, WebLoader, PrecompiledLoader and custom loaders remain application choices.
context
Description: Application defaults and private dependencies. Only inputSchema-declared fields are public defaults; other configured names remain private.
Type: Record<string, unknown>
Accepted by:
- Config: construction
- Template; Script; Function; LLMAgent; Decision (
.asTool;Ordinary+withTemplate,withScript,withFunction,loadsText,loadsTemplate,loadsScript); Embedder (.asTool;Ordinary+withTemplate,withScript,withFunction,loadsText,loadsTemplate,loadsScript); Reranker (.asTool;Ordinary+withTemplate,withScript,withFunction,loadsText,loadsTemplate,loadsScript); ImageGenerator (.asTool;Ordinary+withTemplate,withScript,withFunction,loadsText,loadsTemplate,loadsScript); Transcriber (default source +.asTool;withScript;withFunction;loadsAudio;loadsScript); SpeechGenerator (default source +.asTool;withTemplate;withScript;withFunction;loadsText;loadsTemplate;loadsScript); Translator (default source +.asTool;withScript;withFunction;loadsAudio;loadsScript); VideoGenerator (.asTool;Ordinary+withTemplate,withScript,withFunction,loadsText,loadsTemplate,loadsScript); VoiceAgentBackend (withTemplate,withScript,withFunction,loadsText,loadsTemplate,loadsScript): construction, run, ordinary - Decision (default source +
Ordinary); Embedder (default source +Ordinary); Reranker (default source +Ordinary); ImageGenerator (default source +Ordinary); Transcriber (default source +Ordinary,.asStream); SpeechGenerator (default source +Ordinary,.asStream); Translator (default source +Ordinary,.asStream); VideoGenerator (default source +Ordinary); VoiceAgentBackend (default source): construction, run
Overrides:
- Config: Fixed at construction; derive a component to replace it.
- Context: These are related component settings or injected context values. See the receiving component for its invocation rules.
Inheritance: Shallow merge by key. Call input overrides public defaults; it cannot replace configured private bindings.
Notes: Templates, scripts and functions receive validated input plus private helpers. Direct calls take the component input; use .run({ context }) to supply extra context.
debug
Description: Logs configuration and invocation data for troubleshooting.
Type: boolean | undefined
Default: false
Accepted by:
- All except LLMAgent: construction
- LLMAgent: construction, run
Overrides:
- Config; Template; Script; Function; Decision; Embedder; Reranker; ImageGenerator; Transcriber; SpeechGenerator; Translator; VideoGenerator; VoiceAgentBackend: Fixed at construction; derive a component to replace it.
Notes: Logs are unredacted and can contain headers and private context.
description
Description: Describes the component’s purpose; on a tool it tells the calling model when to use it.
Type: string | ((options: { context: any; experimental_sandbox?: SandboxSession; }) => string) | undefined
Accepted by:
- All except LLMAgent: construction
- LLMAgent: construction, run
Overrides:
- Config; Template; Script; Function; Decision; Embedder; Reranker; ImageGenerator; Transcriber; SpeechGenerator; Translator; VideoGenerator; VoiceAgentBackend: Fixed at construction; derive a component to replace it.
tools
Description:
- All except VoiceAgentBackend: Registers SDK tools. LLMAgent models may choose them; workflows and input preparers call executable tools as functions.
- VoiceAgentBackend: Tools offered in the session and executable through the server’s executeTool adapter.
Type: Record<string, SDK Tool | null | undefined>
Accepted by:
- All except LLMAgent: construction
- LLMAgent: construction, run
Overrides:
- Config; Template; Script; Function; Decision; Embedder; Reranker; ImageGenerator; Transcriber; SpeechGenerator; Translator; VideoGenerator; VoiceAgentBackend: Fixed at construction; derive a component to replace it.
Inheritance: Shallow merge by name; a child null entry removes an inherited tool.
Notes:
- All except VoiceAgentBackend: useTools is an example control, not an API requirement. Specialized models do not gain an LLM tool loop from preparer tools. Registered names cannot be replaced by undeclared public inputs.
- VoiceAgentBackend: Prepared definitions are omitted when empty. Nonempty tools retain provider capability errors. Client-supplied preferences must not replace server-owned tool policy.
toolsContext
Description: Supplies trusted context and declared public defaults for each registered tool.
Type:
- All except LLMAgent:
Record<string, unknown> | undefined - LLMAgent:
ToolContexts<ToolSet> | undefined
Accepted by:
- Config: construction
- Template; Script; Function; LLMAgent; Decision; Embedder; Reranker; ImageGenerator; Transcriber; SpeechGenerator; Translator; VideoGenerator; VoiceAgentBackend: construction, run
Overrides:
- Config: Fixed at construction; derive a component to replace it.
- Context: These are related component settings or injected context values. See the receiving component for its invocation rules.
Inheritance: Shallow merge by tool name. Bound public defaults override the tool’s configured public defaults; explicit payload fields win afterward.
Notes: Supported .run() and method overrides are invocation-local. Bindings must remain compatible with each tool’s context contract.
inputAudioFormat
Description:
- All except VoiceAgentBackend: The input audio format for the raw audio chunks.
- VoiceAgentBackend: Audio format configuration for input audio.
Type: SharedV4AudioFormat | undefined
Values: An audio-format object, for example { type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported.
Required:
- Transcriber: Required by invocation for raw input unless configured. Raw-input tools require it in finished configuration.
- Translator: Required by invocation unless configured; required in finished tool configuration.
Accepted by:
- Config: construction
- Transcriber; Translator: construction, run, ordinary
- VoiceAgentBackend: construction, run
Overrides:
- Config: Fixed at construction; derive a component to replace it.
Notes:
- Config: With .loadsAudio, this is the model target for audio conversion. mediaSettings.format describes the source container instead. The receiving component determines whether a target is required.
- Transcriber: On ordinary Transcriber, this setting selects native streaming execution and a completed transcript. With a PCM target, Casai converts supplied WAV or described PCM in the browser or Node.js. .loadsAudio uses FFmpeg for other codecs; mediaSettings.format describes the source container instead. Completed raw ComponentConfig annotations require this selector.
- Translator: A PCM target specifies the rate for mono PCM16. Casai converts WAV or described PCM to this target. .loadsAudio prepares other encoded media in Node.js.
Native operation:
- Transcriber: experimental_streamTranscribe
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | import("@ai-sdk/provider").SharedV4AudioFormat |
AudioFormat fields |
mediaSettings
Description: Native settings for opening or adapting media and selecting its audio.
Type: { track?: number; format?: string; options?: Record<string, string | number | boolean | bigint | null | undefined> }
Default: Native format detection and best audio stream; supplied-byte inputs deny nested protocol opens unless explicitly configured.
Accepted by:
- Config: construction
- All except Config: construction, run
Overrides: Fixed at construction; derive a component to replace it.
Inheritance: Replaced as a whole object; no deep merge. Constructor undefined uses the ordinary clearing rule. Invocation undefined means omission.
Notes: Configure source credentials here; SDK headers and providerOptions belong to the model request. inputAudioFormat sets the raw model target separately. Tool arguments cannot override mediaSettings. Supplied-byte preparation defaults options.protocol_whitelist to an empty string; a trusted non-null value overrides it. Paths/URLs retain native protocol defaults. No loader configuration is needed. A child changing away from .loadsAudio must clear inherited mediaSettings with undefined.
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | import("../src/audio/preparation.js").MediaSettings |
MediaSettings fields |
fileAudioTarget
Description: Accepted encoded-file target for completed Transcriber.loadsAudio.
Type: FileAudioTarget | undefined
Accepted by: construction, run
Overrides: Fixed at construction; derive a component to replace it.
Inheritance: Replaced as a whole value.
Notes: Configure a native output format and encoder, optional sample constraints and byte/duration limits. Compatible alternatives can be copied, using inspected native metadata. Later playlist format changes may go undetected. Choose a container the SDK can identify, such as WAV or FLAC. An unidentified non-WAV output fails before a provider request. Use this setting for completed file transcription and clear it when switching to raw audio or .withAudio.
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | import("../src/audio/preparation.js").FileAudioTarget |
FileAudioTarget fields |
toolContextSchema
Description: Validates trusted context supplied when binding or executing this tool. It becomes the native tool contextSchema.
Type: Supported schema for trusted tool context
Accepted by:
- Config; Template; Script; Function; LLMAgent; Decision; Embedder; Reranker; ImageGenerator; Transcriber; SpeechGenerator; Translator; VideoGenerator: construction
Overrides:
- All except Context: Fixed at construction; derive a component to replace it.
- Context: These are related component settings or injected context values. See the receiving component for its invocation rules.
Behavior: Casai uses toolContextSchema to distinguish trusted tool context from public inputSchema.
Notes: This is separate from model-controlled arguments. It does not make private context a public input.
onInputAvailable
Description:
Optional function that is called when a tool call can be started, even if the execute function is not provided.
Type: ((options: { input: Record<string, unknown>; } & ToolExecutionOptions<unknown>) => void | PromiseLike<void>) | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
onInputStart
Description:
Optional function that is called when the model starts generating the tool input.
In non-streaming contexts, it is called immediately before onInputAvailable.
Type: ((options: ToolExecutionOptions<unknown>) => void | PromiseLike<void>) | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
onInputDelta
Description:
Optional function that is called when an argument streaming delta is available. Only called when the tool is used in a streaming context.
Type: ((options: { inputTextDelta: string; } & ToolExecutionOptions<unknown>) => void | PromiseLike<void>) | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
needsApproval
Description: Whether the tool needs approval before it can be executed.
Type: boolean | ToolNeedsApprovalFunction<Record<string, unknown>, unknown> | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Deprecated: Tool approval is handled on a generateText / streamText level now.
title
Description: An optional title of the tool.
Type: string | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Deprecated: Use providerMetadata for source-specific tool display metadata.
deferLoading
Description:
Defer exposing this tool until it is discovered by toolSearch.
Supports direct calls and local callers that announce tools in conversation
messages (code mode with toolDiscovery: 'conversation'). Discovered tools
become available on the next model step.
Type: boolean | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
providerOptions
Description:
-
Config; Template; Script; Function:
Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider.
-
LLMAgent; Decision; Embedder; Reranker:
Additional provider-specific options. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider.
-
ImageGenerator:
Additional provider-specific options that are passed through to the provider as body parameters.
The outer record is keyed by the provider name, and the inner record is keyed by the provider-specific metadata key.
{ "openai": { "style": "vivid" } } -
Transcriber (
Ordinary,.asTool):Additional provider-specific options that are passed through to the provider as body parameters.
The outer record is keyed by the provider name, and the inner record is keyed by the provider-specific metadata key.
{ "openai": { "temperature": 0 } } -
Transcriber (
.asStream); SpeechGenerator (.asStream); Translator: Additional provider-specific options. -
SpeechGenerator (
Ordinary,.asTool):Additional provider-specific options that are passed through to the provider as body parameters.
The outer record is keyed by the provider name, and the inner record is keyed by the provider-specific metadata key.
{ "openai": {} } -
VideoGenerator:
Additional provider-specific options that are passed through to the provider as body parameters.
-
VoiceAgentBackend: Provider-specific options that are passed through to the provider.
Type:
- All except VoiceAgentBackend:
SharedV4ProviderOptions | undefined - VoiceAgentBackend:
Record<string, unknown> | undefined
Values:
- Config; Template; Script; Function; LLMAgent; Decision; Embedder; Reranker; ImageGenerator; Transcriber; SpeechGenerator; Translator; VideoGenerator: An object keyed by provider name. Each entry contains settings supported by that provider.
Accepted by:
- Config; Template; Script; Function: construction
- All except Config; Template; Script; Function: construction, run
Overrides:
- Config; Template; Script; Function: Fixed at construction; derive a component to replace it.
Notes: On model-backed components this configures the inner operation. On Template/Script/Function tools it configures the tool descriptor.
Native operation:
- Transcriber (
Ordinary,.asTool): transcribe, experimental_streamTranscribe - Transcriber (
.asStream): experimental_streamTranscribe - SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
metadata
Description:
Optional metadata about the tool itself (e.g. its source).
Unlike providerOptions, this metadata is not sent to the language
model. Instead, it is propagated onto the resulting tool call's
toolMetadata so consumers can read it from tool call / result parts
and UI message parts. This is useful for sources of dynamic tools (e.g.
an MCP server) to identify themselves.
Type: JSONObject | undefined
Values: An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
toModelOutput
Description:
Optional conversion function that maps the tool result to an output that can be used by the language model.
If not provided, the tool result will be sent as a JSON object.
This function is invoked on the server by convertToModelMessages, so ensure that you pass the same "tools" (ToolSet) to both "convertToModelMessages" and "streamText" (or other generation APIs).
Type: ((options: { toolCallId: string; input: Record<string, unknown>; output: unknown; }) => ToolResultOutput | PromiseLike<ToolResultOutput>) | undefined
Required:
- Translator: Optional, including on finished tools.
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Notes:
- LLMAgent: Receives the completed text or parsed structured tool value and replaces its default formatter. Ordinary calls retain the full native result; select files in an explicit Function tool when needed. Explicit formatter composition may call a base formatter.
- Translator: The default sends only translationText to the model. The execution result retains source/translated text and serialized audio for the application and custom formatter. Audio-only output may give empty model text; optionally package audio using its actual known layout. No format guessing, mandatory formatter or new missing-text error.
strict
Description:
Strict mode setting for the tool.
Providers that support strict mode will use this setting to determine how the input should be generated. Strict mode will always produce valid inputs, but it might limit what input schemas are supported.
Type: boolean | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
inputExamples
Description:
An optional list of input examples that show the language model what the input should look like.
Type: { input: NoInfer<Record<string, unknown>>; }[] | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
_toolOptions
Description: Invocation metadata supplied by Casai as context._toolOptions. This is not a configuration property.
Type: ComponentExecutionOptions
Overrides: Injected by Casai; callers cannot replace it.
Notes: Casai injects actual metadata after validation. Ordinary calls have no fabricated toolCallId/messages. Application input and configuration cannot override this binding.
Fields: _toolOptions fields
template
Description:
- Template (default source): The template text.
- Template (
loadsTemplate): The template file name.
Type: string
Required:
- Template (
Ordinary+ default source;.asTool): Required when constructing the finished component, possibly inherited. - Template (
loadsTemplate+Ordinary): Must resolve from configuration or invocation unless an alternative native input satisfies the operation.
Accepted by: construction, run, ordinary
abortSignal
Description: Cooperative cancellation for this invocation.
Type: AbortSignal
Accepted by: run
Inheritance: Never stored in reusable configuration.
Notes: Pass to .run() or a supported native/method call. Forwarded to SDK execution and registered tools; arbitrary application helpers must cooperate themselves.
Native operation:
- Transcriber (
Ordinary,.asTool): transcribe, experimental_streamTranscribe - Transcriber (
.asStream): experimental_streamTranscribe - SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
schema
Description: Parses the Script or Function return value. Stream schemas parse each complete element lazily.
Type: Supported output schema | streamSchema(elementSchema) | textStreamSchema()
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Notes: This is not LLMAgent output, and there is no common outputSchema setting. Declared root streams are collected only during tool execution.
script
Description:
- Script (default source): The script source code.
- Script (
loadsScript): The script file name.
Type: string
Required:
- All except Script (
loadsScript+Ordinary): Required when constructing the finished component, possibly inherited. - Script (
loadsScript+Ordinary): Must resolve from configuration or invocation unless an alternative native input satisfies the operation.
Accepted by: construction, run, ordinary
Notes: Independent operations run concurrently; use ! to sequence intentional effects.
execute
Description: The Function implementation. Receives prepared context with parsed input, dependencies, registered helpers and _toolOptions.
Type: (context: PreparedContext) => Value | PromiseLike<Value> | AsyncIterable<Element>
Values:
The context object passed to the function combines application values, configured private bindings, registered tool helpers and _toolOptions call metadata. Casai validates application values when inputSchema is configured.
Value is the value returned by your implementation. The configured schema, when present, validates or transforms it.
Element is one item produced by an iterable result. A stream schema validates each item.
Required: Required when creating the component, possibly inherited.
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Notes: The implementation is fixed at construction; ordinary and .run() calls supply context, not replacement code.
runtimeContext
Description:
-
LLMAgent:
Runtime context. Treat runtime context as immutable. If you need to mutate runtime context, update it in
prepareStep. -
All except LLMAgent: User-defined runtime context. Treat runtime context as immutable.
Type: Record<string, unknown> | undefined
Accepted by: construction, run
id
Description: The SDK Agent identifier.
Type: string | undefined
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Notes: Tool forms do not expose Agent identity or native generate/stream methods.
output
Description: Optional specification for parsing structured outputs from the LLM response.
Type: AIOutput | undefined
Values: An SDK output specification, such as Output.text() or Output.object({ schema }), which controls how model output is parsed.
Default: Output.text() behavior.
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Notes: Fixed at construction. Generation returns output; streaming returns its final promise and native partial/element views. No extra Casai output schema is applied.
Fields: output fields
maxOutputTokens
Description:
- LLMAgent: Maximum number of tokens to generate.
- Decision: Maximum output tokens for supported models. Must be an integer >= 1.
Type: number | undefined
Accepted by: construction, run
temperature
Description:
Temperature setting. The range depends on the provider and model.
It is recommended to set either temperature or topP, but not both.
Type: number | undefined
Accepted by: construction, run
topP
Description:
Nucleus sampling. This is a number between 0 and 1.
E.g. 0.1 would mean that only tokens with the top 10% probability mass are considered.
It is recommended to set either temperature or topP, but not both.
Type: number | undefined
Accepted by: construction, run
topK
Description:
Only sample from the top K options for each subsequent token.
Used to remove "long tail" low probability responses. Recommended for advanced use cases only. You usually only need to use temperature.
Type: number | undefined
Accepted by: construction, run
presencePenalty
Description:
Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt.
The presence penalty is a number between -1 (increase repetition) and 1 (maximum penalty, decrease repetition). 0 means no penalty.
Type: number | undefined
Accepted by: construction, run
frequencyPenalty
Description:
Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases.
The frequency penalty is a number between -1 (increase repetition) and 1 (maximum penalty, decrease repetition). 0 means no penalty.
Type: number | undefined
Accepted by: construction, run
stopSequences
Description:
Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated. Providers may have limits on the number of stop sequences.
Type: string[] | undefined
Accepted by: construction, run
seed
Description:
-
LLMAgent:
The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results.
-
ImageGenerator: Seed for the image generation. If not provided, the default seed will be used.
-
VideoGenerator: Seed for the video generation.
Type: number | undefined
Accepted by: construction, run
reasoning
Description:
-
LLMAgent:
Reasoning effort level for the model. Controls how much reasoning the model performs before generating a response.
Use
'provider-default'to use the provider's default reasoning level. Use'none'to disable reasoning (if supported by the provider). -
Decision: Reasoning effort for supported models. Language-model adapters default to none.
Type: "provider-default" | "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | undefined
Accepted by: construction, run
maxRetries
Description:
-
LLMAgent: Maximum number of retries. Set to 0 to disable retries.
-
Decision: Maximum retries for transient provider failures. Defaults to 2.
-
Embedder: Maximum number of retries per embedding model call. Set to 0 to disable retries.
-
Reranker: Maximum number of retries per reranking model call. Set to 0 to disable retries.
-
ImageGenerator:
Maximum number of retries per image model call, including retries after unclassified empty responses. Empty responses marked as not retryable by the provider are not retried. Set to 0 to disable retries.
-
Transcriber: Maximum number of retries per transcript model call. Set to 0 to disable retries.
-
SpeechGenerator: Maximum number of retries per speech model call. Set to 0 to disable retries.
-
VideoGenerator: Maximum number of retries per video model call. Set to 0 to disable retries.
Type: number | undefined
Default:
- LLMAgent; Embedder; Reranker; ImageGenerator; Transcriber; SpeechGenerator; VideoGenerator: 2
Accepted by: construction, run
Native operation:
- Transcriber: transcribe
- SpeechGenerator: generateSpeech
headers
Description:
-
LLMAgent; Decision:
Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
-
All except LLMAgent; Decision; Transcriber (
.asStream); SpeechGenerator (.asStream); Translator:Additional headers to include in the request. Only applicable for HTTP-based providers.
-
Transcriber (
.asStream); SpeechGenerator (.asStream); Translator: Additional headers to include in the request, if supported by the provider.
Type:
- LLMAgent:
Record<string, string | undefined> | undefined - All except LLMAgent:
Record<string, string> | undefined
Accepted by: construction, run
Native operation:
- Transcriber (
Ordinary,.asTool): transcribe, experimental_streamTranscribe - Transcriber (
.asStream): experimental_streamTranscribe - SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
timeout
Description: Timeout configuration for the request.
Type: TimeoutConfiguration<ToolSet> | undefined
Accepted by: construction, run
Value shape:
Definition: Timeout
| Shape | Type | Fields |
|---|---|---|
| Alternative 1 | number |
|
| Alternative 2 | Timeout type | Timeout fields (2) |
instructions
Description:
- LLMAgent: Instructions to include in the prompt. Can be used with
promptormessages. - SpeechGenerator: Instructions for the speech generation e.g. "Speak in a slow and steady tone".
- VoiceAgentBackend (default source): Instructions for the voice assistant, supplied by the server.
- VoiceAgentBackend (
withTemplate): Cascada Template text whose variables come from thecontextobject. - VoiceAgentBackend (
withScript): Cascada Script code that calculatesinstructionsusingcontext. - VoiceAgentBackend (
withFunction): A JavaScript function that calculatesinstructionsfromcontext. - VoiceAgentBackend (
loadsText): A file containing instructions for the voice assistant. - VoiceAgentBackend (
loadsTemplate): The name of a Cascada Template file rendered usingcontext. - VoiceAgentBackend (
loadsScript): The name of a Cascada Script file that calculatesinstructions.
Type:
- LLMAgent:
Instructions | undefined - SpeechGenerator; VoiceAgentBackend (default source):
string | undefined - All except LLMAgent; SpeechGenerator; VoiceAgentBackend (default source,
withFunction):string - VoiceAgentBackend (
withFunction):(context: PreparedContext) => string | undefined | PromiseLike<string | undefined>
Values:
- LLMAgent: Instruction text, one system message, or an array of system messages. A system message looks like
{ role: "system", content: "Answer briefly." }. - VoiceAgentBackend (
withFunction): Thecontextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.
Required:
- VoiceAgentBackend: Optional in the direct form. Prepared forms need source in configuration or invocation.
Accepted by:
- LLMAgent; SpeechGenerator: construction, run
- VoiceAgentBackend: construction, run, ordinary
Native operation:
- SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
allowSystemInMessages
Description:
Whether system messages are allowed in the prompt or messages fields.
When disabled, system messages must be provided through the instructions
option.
Type: boolean | undefined
Default: false
Accepted by: construction, run
prompt
Description:
- LLMAgent (default source): Text to send to the model, one message object, or an array of messages. A message contains a role and content, for example { role: "user", content: "Summarize this report." }.
- LLMAgent (
withTemplate); ImageGenerator (withTemplate); VideoGenerator (withTemplate): Cascada Template text whose variables come from thecontextobject. - LLMAgent (
withScript); ImageGenerator (withScript); VideoGenerator (withScript): Cascada Script code that calculatespromptusingcontext. - LLMAgent (
withFunction); ImageGenerator (withFunction); VideoGenerator (withFunction): A JavaScript function that calculatespromptfromcontext. - LLMAgent (
loadsText): A file containing the prompt text to send to the model. - LLMAgent (
loadsTemplate); ImageGenerator (loadsTemplate); VideoGenerator (loadsTemplate): The name of a Cascada Template file rendered usingcontext. - LLMAgent (
loadsScript); ImageGenerator (loadsScript); VideoGenerator (loadsScript): The name of a Cascada Script file that calculatesprompt. - ImageGenerator (default source): An image description, or an object containing text, images and an optional mask. A Cascada Template renders the text; images and masks pass through unchanged.
- ImageGenerator (
loadsText): A file containing the description of the image to generate. - VideoGenerator (default source): The prompt that should be used to generate the video.
- VideoGenerator (
loadsText): A file containing the description of the video to generate.
Type:
- LLMAgent (default source):
PromptValue | undefined - LLMAgent (
withTemplate):PromptValue - LLMAgent (
withScript,loadsText,loadsTemplate,loadsScript); ImageGenerator (withScript,loadsText,loadsTemplate,loadsScript); VideoGenerator (withScript,loadsText,loadsTemplate,loadsScript):string - LLMAgent (
withFunction):(context: PreparedContext) => PromptValue | undefined | PromiseLike<PromptValue | undefined> - ImageGenerator (default source,
withTemplate):GenerateImagePrompt - ImageGenerator (
withFunction):(context: PreparedContext) => GenerateImagePrompt | PromiseLike<GenerateImagePrompt> - VideoGenerator (default source,
withTemplate):GenerateVideoPrompt - VideoGenerator (
withFunction):(context: PreparedContext) => GenerateVideoPrompt | PromiseLike<GenerateVideoPrompt>
Values:
-
LLMAgent (default source,
withTemplate): A text string, one message object, or an array of messages. A message hasroleandcontent, for example{ role: "user", content: "Summarize this report." }. Content may also contain image, file or other parts supported by that role. -
LLMAgent (
withFunction):The
contextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.A text string, one message object, or an array of messages. A message has
roleandcontent, for example{ role: "user", content: "Summarize this report." }. Content may also contain image, file or other parts supported by that role. -
ImageGenerator (default source,
withTemplate): An image description string, or an object with requiredimagesand optionaltextandmask. Each image and the mask can be a base64 string or binary data (Uint8Array,ArrayBufferorBuffer). -
ImageGenerator (
withFunction):The
contextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.An image description string, or an object with required
imagesand optionaltextandmask. Each image and the mask can be a base64 string or binary data (Uint8Array,ArrayBufferorBuffer). -
VideoGenerator (default source,
withTemplate): A video description or an object with an input image and optional text. Image data uses the native DataContent representations. -
VideoGenerator (
withFunction):The
contextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.A video description or an object with an input image and optional text. Image data uses the native DataContent representations.
Required:
- LLMAgent (
Ordinary,.asStream); VideoGenerator (Ordinary;.asTool+ default source): Must resolve from configuration or invocation unless an alternative native input satisfies the operation. - All except LLMAgent (
Ordinary,.asStream); ImageGenerator; VideoGenerator (Ordinary;.asTool+ default source): Required when constructing the finished component, possibly inherited. - ImageGenerator: Text or effective reference images must resolve by invocation.
Accepted by: construction, run, ordinary
Behavior:
- ImageGenerator: Separate configured/invocation media can be composed with text or prepared prompts.
Notes:
- LLMAgent: A Cascada Template renders message text; images, files and other non-text content pass through unchanged. A primary source is separate from a public input field named prompt. Positional message arrays supply history, not newly authored source.
- ImageGenerator: An untouched complete bundle owns its media. Explicit invocation images/mask override it. Use .run() to select structured authored source unambiguously on tools.
- VideoGenerator: Use a string or the native { image, text? } object. Frame and reference settings retain native behavior; no separate image or mask aliases are added.
Value shape:
-
LLMAgent:
Definition:
import("ai").ModelMessageShape Type Fields Alternative 1 import("ai").SystemModelMessageModelMessage fields (1) Alternative 2 import("ai").UserModelMessageModelMessage fields (2) Alternative 3 import("ai").AssistantModelMessageModelMessage fields (3) Alternative 4 import("ai").ToolModelMessageModelMessage fields (4) -
ImageGenerator:
Shape Type Fields A direct or prepared image-prompt object { images: Array<import("ai").DataContent>; text?: string; mask?: import("ai").DataContent; }ImagePrompt fields -
VideoGenerator:
Shape Type Fields Native object prompt { image: import("ai").DataContent; text?: string; }VideoPrompt fields
model
Description:
- LLMAgent: The language model to use.
- Decision: A decision model instance or an ID resolved by the configured default provider.
- Embedder: The embedding model to use.
- Reranker: The reranking model to use.
- ImageGenerator: The image model to use.
- Transcriber: The transcription model to use.
- SpeechGenerator: The speech model to use.
- Translator: The speech translation model to use.
- VideoGenerator: The video model used to generate clips.
- VoiceAgentClient: The browser-compatible realtime model adapter. Keep provider API credentials on the server.
- VoiceAgentBackend: The realtime model used to set up the voice session.
Type:
- LLMAgent:
LanguageModel - Decision:
(DecisionModel | undefined) & DecisionModel - Embedder: model type
- Reranker:
string | RerankingModelV4 | RerankingModelV3 | (string & RerankingModelV4) | (string & RerankingModelV3) | (RerankingModelV4 & string) | (RerankingModelV3 & string) - ImageGenerator: model type
- Transcriber: model type
- SpeechGenerator: model type
- Translator:
(SpeechTranslationModel | undefined) & SpeechTranslationModel - VideoGenerator:
string | VideoModelV4 | VideoModelV3 | (string & VideoModelV4) | (string & VideoModelV3) | (VideoModelV4 & string) | (VideoModelV3 & string) - VoiceAgentClient; VoiceAgentBackend:
RealtimeModelV4
Values:
- LLMAgent: A language-model object created by a provider, or a model identifier resolved by the SDK.
- VoiceAgentClient; VoiceAgentBackend: A realtime model object created by a provider that supports the requested voice-session operation.
Required: Required in the completed component, including inherited settings.
Accepted by:
- All except VoiceAgentClient; VoiceAgentBackend: construction, run
- VoiceAgentClient; VoiceAgentBackend: construction
Overrides:
- VoiceAgentClient; VoiceAgentBackend: Fixed at construction; derive a component to replace it.
Notes: Choose a model that supports the component and requested operation.
Native operation:
- Transcriber (
Ordinary,.asTool): transcribe, experimental_streamTranscribe - Transcriber (
.asStream): experimental_streamTranscribe - SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
toolChoice
Description: The tool choice strategy. Default: 'auto'.
Type: ToolChoice<ToolSet> | undefined
Accepted by: construction, run
telemetry
Description: Optional telemetry configuration.
Type:
- LLMAgent:
TelemetryOptions<Record<string, unknown>, NoInfer<ToolSet>> | undefined - Decision; Embedder; Reranker:
TelemetryOptions<Record<string, unknown>, ToolSet> | undefined - Transcriber; SpeechGenerator:
TelemetryOptions<Context, ToolSet> | undefined
Accepted by: construction, run
Native operation:
- Transcriber (
Ordinary,.asTool): transcribe, experimental_streamTranscribe - Transcriber (
.asStream): experimental_streamTranscribe - SpeechGenerator: generateSpeech
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | Telemetry |
Telemetry fields |
experimental_sandbox
Description: The sandbox environment that is passed through to tool execution.
Type: SandboxSession | undefined
Accepted by: construction, run
experimental_steering
Description:
A steering object created with experimental_createSteering().
Messages sent with it are added to the generation at the next step
boundary.
Type: Steering | undefined
Accepted by: construction, run
activeTools
Description:
Limits the tools that are available for the model to call without changing the tool call and result types in the result.
Type: ActiveTools<NoInfer<ToolSet>>
Accepted by: construction, run
toolOrder
Description:
Controls the order in which tools are sent to the provider.
The list can be partial. Tools not listed in toolOrder are sent after
the listed tools, sorted alphabetically. This can improve provider-side
caching by keeping tool definitions in a stable order.
Type: ToolOrder<NoInfer<ToolSet>>
Accepted by: construction, run
toolCallConcurrency
Description:
Maximum number of tool calls that may execute concurrently within a step.
Set to 1 to execute tool calls sequentially in the order they were
generated. By default, all tool calls execute concurrently.
Type: number | undefined
Accepted by: construction, run
experimental_toolCallers
Description: Configures which caller tools may invoke each tool.
Type: Experimental_ToolCallers<NoInfer<ToolSet>> | undefined
Accepted by: construction, run
experimental_toolApprovalSecret
Description:
Secret for HMAC-signing tool approval requests. When set, the server signs each approval request at issuance and verifies the signature when the approval is replayed, preventing client-forged approvals.
Type: string | Uint8Array<ArrayBufferLike> | undefined
Accepted by: construction, run
include
Description:
Settings for controlling what data is included in step results. Disabling inclusion can help reduce memory usage when processing large payloads like images.
By default, request bodies and request messages are excluded.
Type: StreamTextInclude | undefined
Accepted by: construction, run
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | import("ai").StreamTextInclude |
StreamInclude fields |
streamRetries
Description:
Maximum number of automatic retries for provider errors received after response streaming has started. Each retry reruns only the current model step. Completed earlier steps and their tool results are preserved.
Partial output from a failed attempt that was already emitted cannot be retracted and remains in consumer-facing streams. It is excluded from the recovered step result, structured output parsing, response messages, and subsequent model steps.
Set to 0 to disable automatic retries while allowing onError to
request one retry. When automatic retries are configured, onError can
request at most one additional retry after they are exhausted. Omit this
option to disable all stream retry behavior and preserve incremental tool
streaming for existing onError observers.
Type: number | undefined
Default: 0 (stream retry behavior disabled when omitted)
Accepted by: construction, run
Notes: A streaming-only control. Casai does not add a retry loop; follow the native onError and retry contract.
Native operation: streamText
stopWhen
Description:
Condition for stopping the generation when there are tool results in the last step. When the condition is an array, any of the conditions can be met to stop the generation.
Type: stopWhen type
Default: isStepCount(20), matching ToolLoopAgent.
Accepted by: construction, run
Notes: The limit counts model steps, not individual tool calls; without tool activity, execution normally finishes after one step. Configuration and call settings can replace the default with isStepCount(n) or native predicates. The default is supplied before prepareCall; removing or clearing stopWhen in that hook selects the core SDK’s one-step fallback. A paused turn needs a continuation call; increasing a step limit does not approve tools.
toolApproval
Description:
Optional tool approval configuration.
This configuration takes precedence over tool-defined approval settings.
Type: toolApproval type
Accepted by: construction, run
experimental_download
Description:
Custom download function to use for URLs.
By default, files are downloaded if the model does not support the URL for the given media type.
Type: DownloadFunction | undefined
Values: A function receiving an array of { url, isUrlSupportedByModel } requests. It returns a promise of matching { data, mediaType } download results, or null entries when no data is downloaded. data is a Uint8Array.
Accepted by: construction, run
repairToolCall
Description: A function that attempts to repair a tool call that failed to parse.
Type: repairToolCall type
Accepted by: construction, run
experimental_refineToolInput
Description:
Optional mapping of tool names to functions that refine parsed tool inputs.
The refined input must have the same type shape as the tool input. Refined inputs are used for tool execution, outputs, callbacks, and telemetry.
Type: experimental_refineToolInput type
Accepted by: construction, run
onStart
Description:
-
LLMAgent:
Callback that is called when the generateText operation begins, before any LLM calls are made.
-
Decision: Called when the decide operation begins.
-
Embedder: Callback that is called when the embedding operation begins, before the embedding model is called.
-
Reranker:
Callback that is called when the rerank operation begins, before the reranking model is called.
Type:
- LLMAgent: onStart type
- Decision:
Callback<DecideStartEvent<Record<string, unknown>>> | undefined - Embedder:
Callback<EmbedStartEvent<Record<string, unknown>>> | undefined - Reranker:
Callback<RerankStartEvent<Record<string, unknown>>> | undefined
Values:
- LLMAgent: An SDK output specification, such as
Output.text()orOutput.object({ schema }), which controls how model output is parsed.
Accepted by: construction, run
Notes:
- Embedder: String input uses embed; array input uses embedMany. Callback events follow the selected native operation.
onStepStart
Description:
Callback that is called when a step (LLM call) begins, before the provider is called.
Type: onStepStart type
Values: An SDK output specification, such as Output.text() or Output.object({ schema }), which controls how model output is parsed.
Accepted by: construction, run
onLanguageModelCallStart
Description: Callback that is called immediately before the provider model call begins.
Type: OnLanguageModelCallStartCallback | undefined
Values: A function receiving an event object just before a model request begins. It can return a promise if it needs to do asynchronous work.
Accepted by: construction, run
onLanguageModelCallEnd
Description:
Callback that is called after the model response has been normalized and parsed, but before any client-side tool execution begins.
Type: onLanguageModelCallEnd type
Accepted by: construction, run
onToolExecutionStart
Description: Callback that is called right before a tool's execute function runs.
Type: onToolExecutionStart type
Accepted by: construction, run
onToolExecutionEnd
Description: Callback that is called right after a tool's execute function completes (or errors).
Type: onToolExecutionEnd type
Accepted by: construction, run
onStepEnd
Description: Callback that is called when each step (LLM call) ends, including intermediate steps.
Type: onStepEnd type
Accepted by: construction, run
onStepError
Description:
Callback that is called when a step that started fails before it
produces a step result. onStepEnd is not called for such a step.
Type: onStepError type
Values: An SDK output specification, such as Output.text() or Output.object({ schema }), which controls how model output is parsed.
Accepted by: construction, run
onEnd
Description:
-
LLMAgent: Callback that is called when all steps are finished and the response is complete.
-
Decision: Called when the decide operation completes.
-
Embedder: Callback that is called when the embedding operation completes, after all embedding model calls return.
-
Reranker:
Callback that is called when the rerank operation completes, after the reranking model returns.
Type:
- LLMAgent: onEnd type
- Decision:
Callback<DecideEndEvent<Record<string, unknown>>> | undefined - Embedder:
Callback<EmbedEndEvent<Record<string, unknown>>> | undefined - Reranker:
Callback<RerankEndEvent<Record<string, unknown>>> | undefined
Values:
- LLMAgent: An SDK output specification, such as
Output.text()orOutput.object({ schema }), which controls how model output is parsed.
Accepted by: construction, run
Notes:
- Embedder: String input uses embed; array input uses embedMany. Callback events follow the selected native operation.
experimental_transform
Description:
Optional stream transformations. They are applied in the order they are provided. The stream transformations must maintain the stream structure for streamText to work correctly.
Type: experimental_transform type
Accepted by: construction, run
Native operation: streamText
onChunk
Description:
Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.
Type: onChunk type
Accepted by: construction, run
Native operation: streamText
onError
Description:
-
LLMAgent:
Callback that is invoked when an error occurs during streaming. You can use it to log errors. Return
{ retry: true }to retry the current model step after a provider error is received from the response stream whenstreamRetriesis explicitly configured. The stream processing will pause until the callback promise is resolved. -
SpeechGenerator:
Called for each error part the provider reports. Error parts are not fatal:
fullStreamincludes them andaudioStreamskips them. The callback is not awaited, and errors it throws are ignored. Defaults to logging the error withconsole.error. -
VoiceAgentClient: Called when the realtime session encounters an error.
Type:
- LLMAgent:
StreamTextOnErrorCallback | StreamTextOnErrorRetryCallback | StreamTextOnErrorHandler | undefined - SpeechGenerator:
((event: { error: unknown; }) => void | PromiseLike<void>) | undefined - VoiceAgentClient:
((error: Error) => void) | undefined
Accepted by: construction, run
Native operation:
- LLMAgent: streamText
- SpeechGenerator: experimental_streamSpeech
onAbort
Description: Called when native streaming generation is aborted, with the completed step information available at that point.
Type: onAbort type
Accepted by: construction, run
Native operation: streamText
prepareCall
Description: Transforms the resolved request once before SDK execution.
Type: (request, config, context) => Request | PromiseLike<Request>
Values: Request is the complete set of settings for this component call, including its prepared input. Return the changed request from the hook.
Accepted by: construction, run
Behavior: The three-argument Casai hook receives resolved configuration and prepared application context.
Notes: Return the complete editable request. Omitted editable fields are not restored. Fixed contracts, explicit cancellation, composed observers and approval/telemetry policy remain protected. The retained history is not rewritten by the hook.
prepareStep
Description: Changes supported native settings before an SDK-scheduled model step.
Type: (step, config, context) => NativeStepOverrides | undefined | PromiseLike<...>
Values: An object containing the model-step settings to change, such as model, messages, toolChoice or activeTools. Return undefined to leave them unchanged.
Accepted by: construction, run
Behavior: Retains the SDK name and partial-return contract; Casai adds resolved config and prepared context arguments.
Notes: It does not schedule another step or restart a paused invocation. Return replacements without mutating shared configuration.
messageHistory
Description: Literal earlier conversation messages, followed by the newly prepared prompt. History is never rendered again.
Type: readonly ModelMessage[]
Values: A message object with role (system, user, assistant or tool) and content. For example: { role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed.
Accepted by: run, ordinary
Notes: Positional arrays on LLMAgent are always history. Put newly authored message arrays in config.prompt or .run({ prompt }). Required context comes before positional history.
questions
Description: Named questions describing the requested decisions: category, boolean, score, or supported spatial answer.
Type: Record<string, DecisionModelV4Question>
Required: Required in the completed component.
Accepted by: construction
Overrides: Fixed at construction; derive a component to replace it.
Notes: Question definitions determine answer types and are fixed at construction.
Value shape:
Definition: import("ai").Experimental_DecisionQuestion
| Shape | Type | Fields |
|---|---|---|
| Alternative 1 | DecisionQuestion type | DecisionQuestion fields (1) |
| Alternative 2 | DecisionQuestion type | DecisionQuestion fields (2) |
| Alternative 3 | { readonly type: "box"; readonly instructions: import("@ai-sdk/provider").Experimental_DecisionModelV4Input; } |
DecisionQuestion fields (3) |
| Alternative 4 | DecisionQuestion type | DecisionQuestion fields (4) |
state
Description:
- Decision (default source): The content to evaluate: text, a JSON object, or an array of text, file and JSON parts.
- Decision (
withTemplate): Cascada Template text whose variables come from thecontextobject. - Decision (
withScript): Cascada Script code that calculatesstateusingcontext. - Decision (
withFunction): A JavaScript function that calculatesstatefromcontext. - Decision (
loadsText): A file containing the text to evaluate against the configured questions. - Decision (
loadsTemplate): The name of a Cascada Template file rendered usingcontext. - Decision (
loadsScript): The name of a Cascada Script file that calculatesstate.
Type:
- Decision (default source):
DecisionState - Decision (
withTemplate):string | readonly DecisionStatePart[] - Decision (
withScript,loadsText,loadsTemplate,loadsScript):string - Decision (
withFunction):(context: PreparedContext) => DecisionState | PromiseLike<DecisionState>
Values:
-
Decision (default source): Text, a JSON object, or an ordered array of text, file and JSON parts. For example,
{ type: "text", text: "The delivery arrived late." }supplies text, and{ type: "json", value: { rating: 2 } }supplies JSON. -
Decision (
withTemplate): An object with atypeoftext,fileorjson. Text parts containtext; file parts contain filedataand a media type; JSON parts containvalue. -
Decision (
withFunction):The
contextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.Text, a JSON object, or an ordered array of text, file and JSON parts. For example,
{ type: "text", text: "The delivery arrived late." }supplies text, and{ type: "json", value: { rating: 2 } }supplies JSON.
Required:
- Decision (
Ordinary;.asTool+ default source): Must resolve from configuration or invocation unless an alternative native input satisfies the operation. - All except Decision (
Ordinary;.asTool+ default source): Required when constructing the finished component, possibly inherited.
Accepted by: construction, run, ordinary
experimental_telemetry
Description: Deprecated alias for telemetry. Use telemetry instead.
Type: TelemetryOptions<Record<string, unknown>, ToolSet> | undefined
Accepted by: construction, run
Deprecated: Use telemetry instead. This alias will be removed in a future major release.
Alias: telemetry
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | Telemetry |
Telemetry fields |
experimental_onStart
Description: Deprecated alias for onStart. Use onStart instead.
Type:
- Embedder:
Callback<EmbedStartEvent<Record<string, unknown>>> | undefined - Reranker:
Callback<RerankStartEvent<Record<string, unknown>>> | undefined
Accepted by: construction, run
Deprecated: Use onStart instead.
Alias: onStart
dimensions
Description:
The requested number of dimensions for the output embeddings. Must be a positive integer. Support and allowed values depend on the model and provider implementation.
Type: number | undefined
Accepted by: construction, run
maxParallelCalls
Description:
Maximum number of concurrent requests when a request is split into multiple model calls. Must be greater than 0 when the model supports parallel calls.
Type: number | undefined
Default: Infinity
Accepted by: construction, run
Notes: Relevant to array input. Casai does not add its own batching or concurrency loop.
experimental_onEnd
Description: Deprecated alias for onEnd. Use onEnd instead.
Type:
- Embedder:
Callback<EmbedEndEvent<Record<string, unknown>>> | undefined - Reranker:
Callback<RerankEndEvent<Record<string, unknown>>> | undefined
Accepted by: construction, run
Deprecated: Use onEnd instead.
Alias: onEnd
input
Description:
- Embedder (default source): A string for one embedding or a string array for a batch.
- Embedder (
withTemplate): Cascada Template text whose variables come from thecontextobject. - Embedder (
withScript): Cascada Script code that calculatesinputusingcontext. - Embedder (
withFunction): A JavaScript function that calculatesinputfromcontext. - Embedder (
loadsText): A file containing the text to embed as one vector. - Embedder (
loadsTemplate): The name of a Cascada Template file rendered usingcontext. - Embedder (
loadsScript): The name of a Cascada Script file that calculatesinput.
Type:
- Embedder (default source):
string | string[] - All except Embedder (default source,
withFunction):string - Embedder (
withFunction):(context: PreparedContext) => string | string[] | PromiseLike<string | string[]>
Values:
- Embedder (
withFunction): Thecontextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.
Required:
- Embedder (
Ordinary;.asTool+ default source): Must resolve from configuration or invocation unless an alternative native input satisfies the operation. - All except Embedder (
Ordinary;.asTool+ default source): Required when constructing the finished component, possibly inherited.
Accepted by: construction, run, ordinary
Behavior: Mapped to native embed({ value }) or embedMany({ values }); native results are preserved.
Notes: Inline templates produce one string. Script/function preparers may produce arrays. Configured input permits a no-replacement .run().
documents
Description: Candidate strings or native structured documents to rank.
Type: (string | JSONObject)[] | undefined
Values: An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
Required: Must be available by invocation. A plain tool needs configured documents; a preparer can supply the complete query/documents pair.
Accepted by: construction, run, ordinary
Inheritance: Invocation documents override prepared documents, which override configured candidates.
topN
Description: Number of top documents to return.
Type: number | undefined
Accepted by: construction, run, ordinary
Notes: Available as a positional tail or .run() setting; it is not a public plain-tool argument.
query
Description:
- Reranker (default source): The search text used to rank documents by relevance.
- Reranker (
withTemplate): Cascada Template text whose variables come from thecontextobject. - Reranker (
withScript): Cascada Script code that calculatesqueryusingcontext. - Reranker (
withFunction): A JavaScript function that calculatesqueryfromcontext. - Reranker (
loadsText): A file containing the search query used to rank the candidate documents. - Reranker (
loadsTemplate): The name of a Cascada Template file rendered usingcontext. - Reranker (
loadsScript): The name of a Cascada Script file that calculatesquery.
Type:
- All except Reranker (
withFunction):string - Reranker (
withFunction):(context: PreparedContext) => string | QueryDocuments | PromiseLike<string | QueryDocuments>
Values:
-
Reranker (
withFunction):The
contextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.An object containing both
queryanddocuments. The query is text; each document is text or a JSON object to rank.
Required:
- Reranker (
Ordinary;.asTool+ default source): Must resolve from configuration or invocation unless an alternative native input satisfies the operation. - All except Reranker (
Ordinary;.asTool+ default source): Required when constructing the finished component, possibly inherited.
Accepted by: construction, run, ordinary
Behavior: A script or function can supply both the query and documents in one return value.
n
Description:
- ImageGenerator: Number of images to generate.
- VideoGenerator: Number of videos to generate.
Type: number | undefined
Accepted by: construction, run, ordinary
maxImagesPerCall
Description: Maximum number of images to generate in a single API call. If not provided, the model's default will be used.
Type: number | undefined
Accepted by: construction, run
size
Description: Size of the images to generate. Must have the format {width}x{height}. If not provided, the default size will be used.
Type: size type
Accepted by: construction, run
aspectRatio
Description:
-
ImageGenerator: Aspect ratio of the images to generate. Must have the format
{width}:{height}. If not provided, the default aspect ratio will be used. -
VideoGenerator:
Aspect ratio of the videos to generate. Must have the format
{width}:{height}, or'adaptive'to inherit the ratio from the input media.
Type:
- ImageGenerator: aspectRatio type
- VideoGenerator: aspectRatio type
Accepted by: construction, run
images
Description: Reference images for generation or editing.
Type: DataContent[] | undefined
Values: Binary data supplied as a base64 string, Uint8Array, ArrayBuffer, or Node.js Buffer.
Accepted by: construction, run, ordinary
Inheritance: Constructor values use ordinary replacement and may retain an inherited separate mask. Invocation images replace prior images and drop the previous mask unless that call supplies one.
Behavior: Top-level convenience for the native prompt.images field.
Notes: An empty invocation array clears references; undefined retains them. Text-only updates keep existing media. Complete native bundles retain native empty-array behavior.
mask
Description: An edit mask accompanying reference images; conventions depend on the model.
Type: DataContent | undefined
Values: Binary data supplied as a base64 string, Uint8Array, ArrayBuffer, or Node.js Buffer.
Accepted by: construction, run, ordinary
Inheritance: Mask-only updates retain images. New invocation images drop the old mask unless the call supplies a defined replacement.
Behavior: Top-level convenience for native prompt.mask.
Notes: A separate mask requires at least one reference image. Providers own mask encoding and editing support.
sourceFormat
Description: Original layout of headerless PCM that needs conversion.
Type: PcmSourceFormat | undefined
Accepted by: construction, run
Inheritance: Replaced as a whole value.
Notes: Omit for a WAV, Web Audio AudioBuffer, or media that FFmpeg can probe. For headerless numeric sample arrays, supply sampleRate and channels. For opaque bytes or raw chunk streams, also supply encoding. A direct call can omit sourceFormat for raw bytes already matching inputAudioFormat. FFmpeg needs a source description for headerless media even at the model rate.
Native operation:
- Transcriber (
Ordinary,.asTool): transcribe, experimental_streamTranscribe - Transcriber (
.asStream): experimental_streamTranscribe
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | import("../src/audio/pcm.js").PcmSourceFormat |
PcmSourceFormat fields |
audio
Description:
- Transcriber (default source +
Ordinary,.asTool): A File, Blob, encoded bytes, base64 or URL for file transcription. For raw model input, supply WAV, AudioBuffer, headerless samples or a fresh raw stream. - Transcriber (default source +
.asStream); Translator (default source): WAV, AudioBuffer, headerless PCM, or a fresh stream of raw byte or base64 chunks. - Transcriber (
withScript); Translator (withScript): Cascada Script code that calculatesaudiousingcontext. - Transcriber (
withFunction); Translator (withFunction): A JavaScript function that calculatesaudiofromcontext. - Transcriber (
loadsAudio); Translator (loadsAudio): A file path, URL string/object, encoded Uint8Array/ArrayBuffer or ReadableStreamcontaining media to prepare for the model. - Transcriber (
loadsScript); Translator (loadsScript): The name of a Cascada Script file that calculatesaudio.
Type:
- Transcriber (default source +
Ordinary,.asTool):string | URL | Uint8Array | ArrayBuffer | Blob | File | AudioBuffer | Int16Array | Int32Array | Float32Array | Float64Array | ReadableStream<string | Uint8Array> - Transcriber (default source +
.asStream); Translator (default source):Uint8Array | ArrayBuffer | Blob | File | AudioBuffer | Int16Array | Int32Array | Float32Array | Float64Array | ReadableStream<string | Uint8Array> - Transcriber (
withScript,loadsScript); Translator (withScript,loadsScript):string - Transcriber (
withFunction+Ordinary,.asTool): audio type - Transcriber (
loadsAudio); Translator (loadsAudio):string | URL | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array> - Transcriber (
withFunction+.asStream); Translator (withFunction): audio type
Values:
- Transcriber (
withFunction); Translator (withFunction): Thecontextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.
Required:
- Transcriber (
Ordinary;.asTool+ default source;.asStream); Translator (Ordinary;.asTool+ default source;.asStream): Must resolve from configuration or invocation unless an alternative native input satisfies the operation. - All except Transcriber (
Ordinary;.asTool+ default source;.asStream); Translator (Ordinary;.asTool+ default source;.asStream): Required when constructing the finished component, possibly inherited.
Accepted by: construction, run, ordinary
Notes:
- Transcriber (
Ordinary,.asTool): Node Buffer is a Uint8Array. Casai reads the source layout from a WAV or Web Audio AudioBuffer. Use sourceFormat for headerless PCM that needs conversion. A raw stream without a format is invalid. Native URL objects use the SDK downloader; strings remain encoded audio. .loadsAudio prepares paths/URLs or supplied encoded bytes/byte streams with FFmpeg. .withAudio resets inherited preparation. Plain model tool arguments use URLs through the SDK downloader. .loadsAudio.asTool requires configured audio, including inheritance; model arguments cannot replace it. Trusted ordinary/run calls retain explicit source overrides. Explicit Function/Script workflows handle dynamic native resources and application-defined payloads. - Transcriber (
.asStream): Encoded file data requires .loadsAudio or an explicit preparer. Reusing a known ReadableStream through Casai is rejected. Finite bytes are wrapped in a fresh stream per invocation. - Translator: A completed result requires finite input and native completion. Casai prepares a WAV or AudioBuffer directly, and converts described headerless PCM. Use .loadsAudio for other encoded recordings. Configured finite bytes can be reused; configured streams remain single-use.
Native operation:
- Transcriber (
Ordinary,.asTool): transcribe, experimental_streamTranscribe - Transcriber (
.asStream): experimental_streamTranscribe
download
Description:
-
Transcriber:
Custom download function for fetching audio from URLs. Use
createDownload()fromaito create a download function with custom size limits. -
VideoGenerator:
Custom download function for fetching videos from URLs. Use
createDownload()fromaito create a download function with custom size limits.
Type: ((options: { url: URL; abortSignal?: AbortSignal; }) => Promise<{ data: Uint8Array; mediaType: string | undefined; }>) | undefined
Default: createDownload() (2 GiB limit)
Accepted by: construction, run
Notes:
- Transcriber: Native encoded-file URL download only, with SDK address/redirect and byte-limit handling. The inspected default is 2 GiB; always set an application-appropriate maxBytes for model-selected URLs. Excluded from raw streaming and .loadsAudio, which uses FFmpeg.
- VideoGenerator: The native generated-video download hook. This is separate from .loadsAudio media preparation and does not introduce a general Casai loader.
Native operation:
- Transcriber: transcribe
includeRawChunks
Description: When true, providers should include raw provider chunks in the stream.
Type: boolean | undefined
Accepted by: construction, run
Native operation:
- Transcriber: experimental_streamTranscribe
- SpeechGenerator: experimental_streamSpeech
voice
Description:
- SpeechGenerator: The voice to use for speech generation.
- VoiceAgentBackend: Voice to use for audio output.
Type: string | undefined
Accepted by:
- SpeechGenerator: construction, run, ordinary
- VoiceAgentBackend: construction, run
Native operation:
- SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
outputFormat
Description:
-
SpeechGenerator (
Ordinary,.asTool): A format string for native generateSpeech, or an audio-format object for native streaming. -
SpeechGenerator (
.asStream):The desired format of the output audio chunks, e.g.
{ type: 'audio/pcm', rate: 24000 }or{ type: 'audio/mpeg' }. Supported formats are provider-specific.
Type:
- SpeechGenerator (
Ordinary,.asTool):(string & {}) | SharedV4AudioFormat | "mp3" | "wav" | undefined - SpeechGenerator (
.asStream):SharedV4AudioFormat | undefined
Values: An audio-format object, for example { type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported.
Accepted by: construction, run
Notes:
- SpeechGenerator (
Ordinary,.asTool): With string text, omitting the format or using a string selects generateSpeech. An object, such as { type: "audio/pcm", rate: 24000 }, selects streaming execution and a completed audio file. With iterable/streamed text, use an object or omit the format. To use a streaming-only model with string text, supply an object format. Supported formats depend on the provider. - SpeechGenerator (
.asStream): .asStream selects native streaming even when outputFormat is omitted. Format strings such as "mp3" belong to native generateSpeech; use an object here.
Native operation:
- SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
Value shape:
-
SpeechGenerator (
Ordinary,.asTool):Shape Type Fields Object format import("@ai-sdk/provider").SharedV4AudioFormatSpeechAudioFormat fields -
SpeechGenerator (
.asStream):Shape Type Fields Value import("@ai-sdk/provider").SharedV4AudioFormatSpeechAudioFormat fields
speed
Description: The speed of the speech generation.
Type: number | undefined
Accepted by: construction, run
Native operation:
- SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
language
Description:
The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") or "auto" for automatic language detection. Provider support varies.
Type: string | undefined
Accepted by: construction, run
Native operation:
- SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
text
Description:
-
SpeechGenerator (default source):
The text to convert to speech: a complete string, or an array, iterable, or stream of text deltas and/or text parts.
-
SpeechGenerator (
withTemplate): Cascada Template text whose variables come from thecontextobject. -
SpeechGenerator (
withScript): Cascada Script code that calculatestextusingcontext. -
SpeechGenerator (
withFunction): A JavaScript function that calculatestextfromcontext. -
SpeechGenerator (
loadsText): A file containing the text to read aloud. -
SpeechGenerator (
loadsTemplate): The name of a Cascada Template file rendered usingcontext. -
SpeechGenerator (
loadsScript): The name of a Cascada Script file that calculatestext.
Type:
- SpeechGenerator (default source):
string | Iterable<string | SpeechTextPart> | AsyncIterable<string | SpeechTextPart> | ReadableStream<string | SpeechTextPart> - All except SpeechGenerator (default source,
withFunction):string - SpeechGenerator (
withFunction): text type
Values:
-
SpeechGenerator (default source): A text chunk such as
{ type: "text", text: "Hello" }. It can also specify avoiceandproviderOptionsfor that chunk. -
SpeechGenerator (
withFunction):The
contextobject passed to the function combines application values, configured private bindings, registered tool helpers and_toolOptionscall metadata. Casai validates application values wheninputSchemais configured.A text chunk such as
{ type: "text", text: "Hello" }. It can also specify avoiceandproviderOptionsfor that chunk.
Required:
- SpeechGenerator (
Ordinary;.asTool+ default source;.asStream): Must resolve from configuration or invocation unless an alternative native input satisfies the operation. - All except SpeechGenerator (
Ordinary;.asTool+ default source;.asStream): Required when constructing the finished component, possibly inherited.
Accepted by: construction, run, ordinary
Notes:
- SpeechGenerator (
Ordinary,.asTool): A script or function preparer may return a fresh text stream. Non-string input requires native streaming support; an ordinary call collects the generated audio into a file. Text-part objects belong inside an iterable or stream. - SpeechGenerator (
.asStream): A script or function preparer may return a fresh text stream. Text-part objects belong inside an iterable or stream.
Native operation:
- SpeechGenerator (
Ordinary,.asTool): generateSpeech, experimental_streamSpeech - SpeechGenerator (
.asStream): experimental_streamSpeech
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Each text part in an iterable or stream | import("ai").Experimental_SpeechTextPart |
SpeechTextPart fields |
targetLanguage
Description:
The language to translate the audio into, as a BCP-47-style language
tag (e.g. en, es, fr-CA). Supported values are provider-specific
and validated by the provider.
Type: string | undefined
Required: Required by invocation unless configured; required in finished tool configuration.
Accepted by: construction, run, ordinary
outputAudioFormat
Description:
-
Translator:
The desired audio format for translated audio chunks. When absent, the provider default output format is used.
-
VoiceAgentBackend: Audio format configuration for output audio.
Type: SharedV4AudioFormat | undefined
Values: An audio-format object, for example { type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported.
Accepted by: construction, run
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | import("@ai-sdk/provider").SharedV4AudioFormat |
AudioFormat fields |
sourceLanguage
Description:
The language of the source audio, as a BCP-47-style language tag. When absent, providers auto-detect the source language.
Type: string | undefined
Accepted by: construction, run
maxVideosPerCall
Description: Maximum number of videos per API call. If not provided, the model's default will be used.
Type: number | undefined
Accepted by: construction, run
resolution
Description: Resolution of the videos to generate. Must have the format {width}x${height}.
Type: resolution type
Accepted by: construction, run
duration
Description: Duration of the video in seconds.
Type: number | undefined
Accepted by: construction, run
fps
Description: Frames per second for the video.
Type: number | undefined
Accepted by: construction, run
frameImages
Description: Role-tagged image inputs for image-to-video and first-last-frame generation.
Type: { image: DataContent; frameType: VideoModelV4FrameType; }[] | undefined
Values: Binary data supplied as a base64 string, Uint8Array, ArrayBuffer, or Node.js Buffer.
Accepted by: construction, run
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Each role-tagged frame | { image: import("ai").DataContent; frameType: import("@ai-sdk/provider").Experimental_VideoModelV4FrameType; } |
VideoFrame fields |
inputReferences
Description:
Reference inputs for reference-to-video generation.
Each entry may be a plain image/video ({@link DataContent}), or an object
form that carries an explicit mediaType.
Type: (DataContent | { data: DataContent; mediaType?: string; })[] | undefined
Values: Binary data supplied as a base64 string, Uint8Array, ArrayBuffer, or Node.js Buffer.
Accepted by: construction, run
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Object-form reference input; raw DataContent is also accepted | { data: import("ai").DataContent; mediaType?: string; } |
VideoReference fields |
generateAudio
Description: Whether the model should generate audio alongside the video.
Type: boolean | undefined
Accepted by: construction, run
poll
Description:
Polling configuration for models that support the asynchronous
start/status flow. When provided and the model implements doStart
and doStatus, the SDK will orchestrate polling automatically.
This option can be combined with webhook: timeoutMs limits the webhook
wait, and the polling settings apply if the model does not support
webhooks.
Type: GenerateVideoPollOptions | undefined
Accepted by: construction, run
Notes: Delegated to the SDK. Native capability selection and warnings apply; this does not select streaming output or create a Casai job manager.
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | { intervalMs?: number; timeoutMs?: number; delay?: (delayInMs: number, options?: { abortSignal?: AbortSignal; }) => PromiseLike<void>; } |
VideoPoll fields |
webhook
Description:
Webhook factory for models that support the asynchronous
start/status flow. When provided and the model implements doStart
and doStatus, the SDK will use webhooks instead of polling.
The factory should return a URL for the provider to send notifications to,
and a received promise that resolves when the notification arrives.
poll can also be provided to configure the webhook timeout and polling
fallback.
Type: GenerateVideoWebhookFactory | undefined
Accepted by: construction, run
Notes: An application-owned native webhook factory. Keep it in trusted configuration or invocation settings, outside model arguments.
api
Description: websocket uses a raw-protocol relay; session exchanges SDP; token fetches client-secret setup.
Type: api type
Required: Required when constructing the finished component, possibly inherited.
Accepted by: construction, run
Notes: Application routes own authentication and authorization. Native fetch/WebSocket restrictions apply; this component adds no custom headers, fetch implementation or authentication protocol.
Value shape:
Definition: VoiceClientApi type
| Shape | Type | Fields |
|---|---|---|
| Alternative 1 | { token: string; session?: never; websocket?: never; protocols?: never; } |
VoiceClientApi fields (1) |
| Alternative 2 | { session: string; token?: never; websocket?: never; protocols?: never; } |
VoiceClientApi fields (2) |
| Alternative 3 | { websocket: string; protocols?: string[]; token?: never; session?: never; } |
VoiceClientApi fields (3) |
sessionConfig
Description: Provider-neutral session configuration, such as instructions, voice, audio formats, input audio transcription, turn detection, tools, and providerOptions.
Type: Partial<RealtimeModelV4SessionConfig> | undefined
Accepted by: construction, run
Notes: Public browser preferences only. Share an explicit typed public object when useful; do not inherit the backend configuration. Replacements use whole-value semantics.
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | import("@ai-sdk/provider").Experimental_RealtimeModelV4SessionConfig |
VoiceClientSessionConfig fields |
sampleRate
Description: Default audio sample rate used when inputAudioFormat.rate or outputAudioFormat.rate is not specified. Defaults to 24000.
Type: number | undefined
Accepted by: construction, run
maxEvents
Description: Maximum number of provider events to keep in the events array. Defaults to 500.
Type: number | undefined
Accepted by: construction, run
startupTimeoutMs
Description: Maximum time to establish transport and receive readiness. Default: 30s.
Type: number | undefined
Accepted by: construction, run
closeTimeoutMs
Description: Maximum wait for final usage after close(). Default: 15s.
Type: number | undefined
Accepted by: construction, run
rtcDisconnectTimeoutMs
Description: WebRTC peer disconnect recovery grace period. Default: 5s.
Type: number | undefined
Accepted by: construction, run
maxPlaybackBufferSeconds
Description: Continuous PCM only: pause at this budget until resumePlayback(). Default: 2s.
Type: number | undefined
Accepted by: construction, run
onToolCall
Description: Turn-based tools only. Return a value to automatically submit it as tool output, or return undefined and call addToolOutput manually later. Live client delegations are application-handled through session metadata and events.
Type: ((args: { toolCall: { toolCallId: string; toolName: string; args: unknown; }; }) => Promise<unknown> | unknown | undefined) | undefined
Accepted by: construction, run
Notes: The application handles local actions or calls an authorized backend executeTool route. This is a native callback, not a Casai tools registry.
onEvent
Description: Called for every normalized realtime server event.
Type: ((event: RealtimeServerEvent) => void) | undefined
Accepted by: construction, run
outputModalities
Description: Which output modalities the model should produce.
Type: ("text" | "audio")[] | undefined
Accepted by: construction, run
inputAudioTranscription
Description:
Input audio transcription configuration.
When enabled, providers that support input transcription emit normalized
input-transcription-completed events that can be rendered as user
messages.
Type: { model?: string; language?: string; prompt?: string; } | undefined
Accepted by: construction, run
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | { model?: string; language?: string; prompt?: string; } |
SessionTranscription fields |
outputAudioTranscription
Description:
Output audio transcription configuration.
When enabled, providers that support output transcription emit normalized
audio-transcript-delta / audio-transcript-done events for the model's
spoken response. Some providers transcribe output by default; setting this
makes the behavior explicit rather than relying on that default.
Type: { model?: string; language?: string; prompt?: string; } | undefined
Accepted by: construction, run
Value shape:
| Shape | Type | Fields |
|---|---|---|
| Value | { model?: string; language?: string; prompt?: string; } |
SessionTranscription fields |
turnDetection
Description:
Voice activity detection configuration. Set to null or type 'disabled' to turn off VAD (push-to-talk mode).
Type: { type: "server-vad" | "semantic-vad" | "disabled"; threshold?: number; silenceDurationMs?: number; prefixPaddingMs?: number; } | null | undefined
Accepted by: construction, run
Value shape:
Definition: TurnDetection
| Shape | Type | Fields |
|---|---|---|
| Alternative 1 | null |
|
| Alternative 2 | { type: "server-vad" | "semantic-vad" | "disabled"; threshold?: number; silenceDurationMs?: number; prefixPaddingMs?: number; } |
TurnDetection fields (2) |
expiresAfterSeconds
Description: Requests the client-secret lifetime supported by the model.
Type: number | undefined
Accepted by: construction, run
Notes: Applies to ordinary/token calls, not to session configuration or WebRTC negotiation.
Native operation: doCreateClientSecret
Calls and methods
Use the component tables above to check which methods are available. .run() accepts exactly the settings marked run in the applicable property contract. Other methods list their supported settings below.
call
Signature:
- Template:
template(context?) or template(source, context?) - Script:
script(context?) or script(source, context?) - Function:
fn(context?) - LLMAgent:
agent(prompt?, context?, messageHistory?) - Decision:
decide(state) or decide(context) - Embedder:
embed(input) or embed(context) - Reranker:
rank(query, documents?, topN?) or rank(context, documents?, topN?) - ImageGenerator:
draw(text?, images?, mask?, n?) or draw(context, images?, mask?, n?) - Transcriber:
transcribe(audio, inputAudioFormat?) or transcribe(context, inputAudioFormat?) - SpeechGenerator:
speak(text, voice?) or speak(context, voice?) - Translator:
translate(audio, inputAudioFormat?, targetLanguage?) or translate(context, inputAudioFormat?, targetLanguage?) - VideoGenerator:
generate(prompt?, n?) or generate(context, n?) - VoiceAgentClient:
client() - VoiceAgentBackend:
setup(instructions?) or setup(context)
Behavior:
- All except VoiceAgentClient: Shorthand invocation: pass the main arguments directly in the order shown.
component(input)and the correspondingcomponent.run({ ... })call execute the same component and return the same kind of result. You can omit configured arguments when the remaining argument types are unambiguous. - VoiceAgentClient: Creates a new disconnected session from the reusable configuration, without connecting or accessing the microphone. Returns a promise for the session.
run
Signature:
- All except VoiceAgentClient:
component.run({ context?, ...supportedInputsAndOverrides }) - VoiceAgentClient:
client.run(settings?)
Behavior:
- All except VoiceAgentClient: Pass the component's input properties by name, such as
prompt,input,textoraudio. Pass structured application data undercontext. You can also include supported per-call settings, such asabortSignal, without changing the reusable configuration. Supply required values that are not already configured. - VoiceAgentClient: Creates a new disconnected session with native option overrides, except the fixed model. Omitted options inherit; supplied values replace whole values, including api and sessionConfig. Configuration and other sessions are unchanged.
config
Signature:
- Config:
fragment.config - All except Config:
component.config
Behavior:
- Config: The resolved reusable fragment. Pass the fragment as a parent; treat captured configuration as immutable.
- All except Config: The resolved configuration. Treat it as immutable; construct a new component to replace captured dependencies.
Config
Signature: Config(settings, parent?)
Behavior: Creates a reusable fragment. Missing required settings are checked on the eventual component; the merged settings must fit one compatible component shape.
withText
Signature: Config.withText(settings, parent?)
Behavior: Selects the same source interpretation as the component's .withText modifier. The explicit selection replaces an inherited source mode. A fragment may leave the source or required text loader for its consuming component.
withTemplate
Signature: Config.withTemplate(settings, parent?)
Behavior: Selects the same source interpretation as the component's .withTemplate modifier. The explicit selection replaces an inherited source mode. A fragment may leave the source or required text loader for its consuming component.
withScript
Signature: Config.withScript(settings, parent?)
Behavior: Selects the same source interpretation as the component's .withScript modifier. The explicit selection replaces an inherited source mode. A fragment may leave the source or required text loader for its consuming component.
withFunction
Signature: Config.withFunction(settings, parent?)
Behavior: Selects the same source interpretation as the component's .withFunction modifier. The explicit selection replaces an inherited source mode. A fragment may leave the source or required text loader for its consuming component.
loadsText
Signature: Config.loadsText(settings, parent?)
Behavior: Selects the same source interpretation as the component's .loadsText modifier. The explicit selection replaces an inherited source mode. A fragment may leave the source or required text loader for its consuming component.
loadsTemplate
Signature: Config.loadsTemplate(settings, parent?)
Behavior: Selects the same source interpretation as the component's .loadsTemplate modifier. The explicit selection replaces an inherited source mode. A fragment may leave the source or required text loader for its consuming component.
loadsScript
Signature: Config.loadsScript(settings, parent?)
Behavior: Selects the same source interpretation as the component's .loadsScript modifier. The explicit selection replaces an inherited source mode. A fragment may leave the source or required text loader for its consuming component.
loadsAudio
Signature: Config.loadsAudio(settings, parent?)
Behavior: Selects the same source interpretation as the component's .loadsAudio modifier. The explicit selection replaces an inherited source mode. A fragment may leave the media location and input settings for its consuming component; no loader setting is needed.
asTool
Signature: Config[.sourceModifier].asTool(settings, parent?)
Behavior: Enables tool mode on the consuming component. For example, Config.withTemplate.asTool combines template preparation with tool adaptation. The fragment itself is not executable; the completed component must supply a closed inputSchema and its other tool requirements.
asStream
Signature: Config[.sourceModifier].asStream(settings, parent?)
Behavior: Enables streaming output on a compatible consuming component. For example, Config.withFunction.asStream prepares input for a streaming component with a function. Streaming and tool modifiers cannot be combined. Select the source first, then .asTool or .asStream; reverse chains are not provided.
bindToolContext
Signature: component.bindToolContext(trustedContext)
Behavior: Returns { tool, context } with validated trusted bindings and declared public defaults. Use the bound descriptor and matching context for SDK execution.
execute
Signature: tool.execute(parsedInput, nativeToolOptions)
Behavior: Native SDK descriptor entry: input is already parsed by the owning SDK path. Ordinary component calls validate raw input; do not use descriptor execution to bypass that boundary.
id
Signature: agent.id
Behavior: The configured SDK Agent ID, or undefined.
version
Signature: agent.version
Behavior: The native Agent protocol marker: agent-v1.
tools
Signature: agent.tools
Behavior: The prepared SDK tool definitions used by Agent integrations, including their argument schemas and available executors. Defaults to an empty object.
resume
Signature: agent.resume(history, { context?, approve?, ...overrides }?)
Behavior: Continues a saved conversation without preparing another source. It also supports provider pauses and deferred results; tools are needed only for the approval example. Supply required raw context and any per-call overrides again.
Settings: context, debug, description, tools, toolsContext, runtimeContext, providerOptions, maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, stopSequences, seed, reasoning, maxRetries, headers, timeout, instructions, allowSystemInMessages, model, toolChoice, telemetry, experimental_sandbox, experimental_steering, activeTools, toolOrder, toolCallConcurrency, experimental_toolCallers, experimental_toolApprovalSecret, include, streamRetries, stopWhen, toolApproval, experimental_download, repairToolCall, experimental_refineToolInput, onStart, onStepStart, onLanguageModelCallStart, onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, onStepEnd, onStepError, onEnd, experimental_transform, onChunk, onError, onAbort, prepareCall, prepareStep, abortSignal
Additional inputs: resume inputs
generate
Signature: agent.generate({ prompt? | messages?, options?, ...settings })
Behavior: Runs the native SDK Agent generation method. Content is literal: source loading/rendering is skipped. options supplies application input and still passes through Casai context validation and hooks.
Arguments: generate arguments
Returns: generate result
Additional fields: generate additional fields
stream
Signature: agent.stream({ prompt? | messages?, options?, ...settings })
Behavior: Runs the native streaming Agent method, even when ordinary calls use generation. It shares the same validated context and hooks and skips source preparation.
Arguments: stream arguments
Returns: stream result
Additional fields: stream additional fields
prepareSessionConfig
Signature: setup.prepareSessionConfig(settings?)
Behavior: Prepares instructions and tool definitions without opening a provider session. Empty tool definitions are omitted.
Settings: providerOptions, inputAudioFormat, voice, outputModalities, inputAudioTranscription, outputAudioTranscription, outputAudioFormat, turnDetection, instructions, context, toolsContext, abortSignal
Returns: prepareSessionConfig result
createWebRTCSession
Signature: setup.createWebRTCSession({ sdp, ...settings })
Behavior: Answers a browser SDP offer using the configured model.
Settings: providerOptions, inputAudioFormat, voice, outputModalities, inputAudioTranscription, outputAudioTranscription, outputAudioFormat, turnDetection, instructions, context, toolsContext, abortSignal
Additional inputs: createWebRTCSession inputs
Returns: createWebRTCSession result
executeTool
Signature: setup.executeTool({ toolCallId, toolName, args }, { toolsContext?, abortSignal? }?)
Behavior: Validates and executes a registered server tool with the real call metadata and trusted context. Returns the tool execution value without language-model toModelOutput formatting. Applications own HTTP transport and map undefined results to JSON null.
Settings: toolsContext, abortSignal
Additional inputs: executeTool inputs
Shared types and result fields
Nested shapes and long TypeScript signatures are defined once here. Separate alternatives remain separate; fields from different alternatives are not interchangeable. Native SDK fields retain their documented behavior.
LLMAgent
-
content:ContentPart<ToolSet>[]. The content that was generated in all steps. -
text:string. The concatenation of all text parts generated in the final step. It is an empty string if the final step contains no text parts. InspectfinalStep.contentto distinguish that case. -
reasoning:(ReasoningOutput | ReasoningFileOutput)[]. The full reasoning that the model has generated in the last step.deprecated: Use
finalStep.reasoninginstead. -
reasoningText:string | undefined. The reasoning text that the model has generated in the last step. Can be undefined if the model has only generated text.deprecated: Use
finalStep.reasoningTextinstead. -
files:GeneratedFile[]. The files that were generated in all steps. Empty array if no files were generated. -
sources:LanguageModelV4Source[]. Sources that have been used as references in all steps. -
toolCalls:TypedToolCall<ToolSet>[]. The tool calls that were made in all steps. -
staticToolCalls:(BaseToolCall & { toolName: string; input: any; dynamic?: false | undefined; invalid?: false | undefined; error?: never; title?: string; })[]. The static tool calls that were made in all steps. -
dynamicToolCalls:DynamicToolCall[]. The dynamic tool calls that were made in all steps. -
toolResults:TypedToolResult<ToolSet>[]. The results of the tool calls from all steps. -
staticToolResults: staticToolResults type. The static tool results that were made in all steps.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
dynamicToolResults:DynamicToolResult[]. The dynamic tool results that were made in all steps. -
finishReason:FinishReason. The unified reason why the generation finished. -
rawFinishReason:string | undefined. The raw reason why the generation finished (from the provider). -
usage:LanguageModelUsage. The total token usage of all steps. When there are multiple steps, the usage is the sum of all step usages. -
totalUsage:LanguageModelUsage. The total token usage of all steps. When there are multiple steps, the usage is the sum of all step usages.deprecated: Use
usageinstead. -
warnings:SharedV4Warning[] | undefined. Warnings from the model provider (e.g. unsupported settings) in all steps. -
request:LanguageModelRequestMetadata. Additional request information from the last step.deprecated: Use
finalStep.requestinstead. -
response:LanguageModelResponseMetadata. Additional response information from the last step.deprecated: Use
finalStep.responseinstead. -
responseMessages:ResponseMessage[]. The accumulated response messages of all steps that were generated during the call. -
providerMetadata:SharedV4ProviderMetadata | undefined. Additional provider-specific metadata from the final step. They are passed through from the provider to the AI SDK and enable provider-specific results that can be fully encapsulated in the provider.deprecated: Use
finalStep.providerMetadatainstead. -
steps:StepResult<ToolSet, Context>[]. Details for all steps. You can use this to get information about intermediate steps, such as the tool calls or the response headers. -
finalStep:StepResult<ToolSet, Context>. The final step. This is a shortcut forsteps.at(-1). -
output:any. The generated output according to theoutputspecification.
LLMAgentStream
-
content:PromiseLike<ContentPart<ToolSet>[]>. The content that was generated in all steps.Automatically consumes the stream.
-
text:PromiseLike<string>. The full text that has been generated by the final step.Automatically consumes the stream.
-
reasoning:PromiseLike<(ReasoningOutput | ReasoningFileOutput)[]>. The full reasoning that the model has generated.Automatically consumes the stream.
deprecated: Use
finalStep.reasoninginstead. -
reasoningText:PromiseLike<string | undefined>. The reasoning that has been generated by the last step.Automatically consumes the stream.
deprecated: Use
finalStep.reasoningTextinstead. -
files:PromiseLike<GeneratedFile[]>. Files that have been generated by the model in all steps.Automatically consumes the stream.
-
sources:PromiseLike<LanguageModelV4Source[]>. Sources that have been used as references in all steps.Automatically consumes the stream.
-
toolCalls:PromiseLike<TypedToolCall<ToolSet>[]>. The tool calls that have been executed in all steps.Automatically consumes the stream.
-
staticToolCalls:PromiseLike<(BaseToolCall & { toolName: string; input: any; dynamic?: false | undefined; invalid?: false | undefined; error?: never; title?: string; })[]>. The static tool calls that have been executed in all steps.Automatically consumes the stream.
-
dynamicToolCalls:PromiseLike<DynamicToolCall[]>. The dynamic tool calls that have been executed in all steps.Automatically consumes the stream.
-
staticToolResults: staticToolResults type. The static tool results that have been generated in all steps.Automatically consumes the stream.
An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
dynamicToolResults:PromiseLike<DynamicToolResult[]>. The dynamic tool results that have been generated in all steps.Automatically consumes the stream.
-
toolResults:PromiseLike<TypedToolResult<ToolSet>[]>. The tool results that have been generated in all steps.Automatically consumes the stream.
-
finishReason:PromiseLike<FinishReason>. The unified finish reason why the generation finished. Taken from the last step.Automatically consumes the stream.
-
rawFinishReason:PromiseLike<string | undefined>. The raw reason why the generation finished (from the provider). Taken from the last step.Automatically consumes the stream.
-
usage:PromiseLike<LanguageModelUsage>. The total token usage of the generated response. When there are multiple steps, the usage is the sum of all step usages.Automatically consumes the stream.
-
totalUsage:PromiseLike<LanguageModelUsage>. The total token usage of the generated response. When there are multiple steps, the usage is the sum of all step usages.Automatically consumes the stream.
deprecated: Use
usageinstead. -
warnings:PromiseLike<SharedV4Warning[] | undefined>. Warnings from the model provider (e.g. unsupported settings) in all steps.Automatically consumes the stream.
-
steps:PromiseLike<StepResult<ToolSet, Context>[]>. Details for all steps. You can use this to get information about intermediate steps, such as the tool calls or the response headers.Automatically consumes the stream.
-
finalStep:PromiseLike<StepResult<ToolSet, Context>>. The final step. This is a shortcut forsteps.at(-1).Automatically consumes the stream.
-
request:PromiseLike<LanguageModelRequestMetadata>. Additional request information from the last step.Automatically consumes the stream.
deprecated: Use
finalStep.requestinstead. -
response:PromiseLike<LanguageModelResponseMetadata>. Additional response information from the last step.Automatically consumes the stream.
deprecated: Use
finalStep.responseinstead. -
responseMessages:PromiseLike<ResponseMessage[]>. The accumulated response messages of all steps that were generated during the call.Automatically consumes the stream.
-
providerMetadata:PromiseLike<SharedV4ProviderMetadata | undefined>. Additional provider-specific metadata from the last step. Metadata is passed through from the provider to the AI SDK and enables provider-specific results that can be fully encapsulated in the provider.deprecated: Use
finalStep.providerMetadatainstead. -
textStream:AsyncIterableStream<string>. A text stream that returns only the generated text deltas. You can use it as either an AsyncIterable or a ReadableStream. Error parts are not surfaced in this stream. Use theonErrorcallback orstreamto observe them. -
stream:AsyncIterableStream<TextStreamPart<ToolSet>>. A stream with all events, including text deltas, tool calls, tool results, and errors. You can use it as either an AsyncIterable or a ReadableStream. Only errors that stop the stream, such as network errors, are thrown. -
fullStream:AsyncIterableStream<TextStreamPart<ToolSet>>. A stream with all events, including text deltas, tool calls, tool results, and errors. You can use it as either an AsyncIterable or a ReadableStream. Only errors that stop the stream, such as network errors, are thrown.deprecated: Use
streaminstead. -
experimental_partialOutputStream:AsyncIterableStream<any>. A stream of partial outputs. It uses theoutputspecification.deprecated: Use
partialOutputStreaminstead. -
partialOutputStream:AsyncIterableStream<any>. A stream of partial parsed outputs. It uses theoutputspecification. -
elementStream:AsyncIterableStream<any>. A stream of individual array elements as they complete. Only available when usingoutput: Output.array(). -
output:PromiseLike<any>. The complete parsed output. It uses theoutputspecification. -
consumeStream:(options?: ConsumeStreamOptions) => PromiseLike<void>. Consumes the stream without processing the parts. This is useful to force the stream to finish. It effectively removes the backpressure and allows the stream to finish, triggering theonEndcallback and the promise resolution.If an error occurs, it is passed to the optional
onErrorcallback. -
toUIMessageStream:<UI_MESSAGE extends UIMessage>(options?: UIMessageStreamOptions<UI_MESSAGE>) => AsyncIterableStream<InferUIMessageChunk<UI_MESSAGE>>. Converts the result to a UI message stream.returns: A UI message stream.
deprecated: Use the standalone
toUIMessageStreamhelper from'ai'withresult.streaminstead. This method will be removed in the next major release. -
pipeUIMessageStreamToResponse:<UI_MESSAGE extends UIMessage>(response: ServerResponse, options?: UIMessageStreamResponseInit & UIMessageStreamOptions<UI_MESSAGE>) => Promise<void>. Writes UI message stream output to a Node.js response-like object.deprecated: Use the standalone
toUIMessageStreamandpipeUIMessageStreamToResponsehelpers from'ai'withresult.streaminstead. This method will be removed in the next major release. -
pipeTextStreamToResponse:(response: ServerResponse, init?: ResponseInit) => Promise<void>. Writes text delta output to a Node.js response-like object. It sets aContent-Typeheader totext/plain; charset=utf-8and writes each text delta as a separate chunk.param: response A Node.js response-like object (ServerResponse).
param: init Optional headers, status code, and status text.
deprecated: Use the standalone
toTextStreamandpipeTextStreamToResponsehelpers from'ai'withresult.streaminstead. This method will be removed in the next major release. -
toUIMessageStreamResponse:<UI_MESSAGE extends UIMessage>(options?: UIMessageStreamResponseInit & UIMessageStreamOptions<UI_MESSAGE>) => Response. Converts the result to a streamed response object with a stream data part stream.returns: A response object.
deprecated: Use the standalone
toUIMessageStreamandcreateUIMessageStreamResponsehelpers from'ai'withresult.streaminstead. This method will be removed in the next major release. -
toTextStreamResponse:(init?: ResponseInit) => Response. Creates a simple text stream response. Each text delta is encoded as UTF-8 and sent as a separate chunk. Non-text-delta events are ignored.param: init Optional headers, status code, and status text.
deprecated: Use the standalone
toTextStreamandcreateTextStreamResponsehelpers from'ai'withresult.streaminstead. This method will be removed in the next major release.
LLMAgent additional result fields
-
messageHistory:ModelMessage[]. The original conversation followed by the SDK response messages. Changes a hook makes to the provider request do not rewrite this history. Casai adds this field to the SDK result.A message object with
role(system,user,assistantortool) andcontent. For example:{ role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed.
LLMAgent additional result fields
-
messageHistory:Promise<ModelMessage[]>. Resolves to the original conversation followed by the SDK response messages from the same execution. History can still be available when parsing the final output fails.A message object with
role(system,user,assistantortool) andcontent. For example:{ role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed.
Decision
-
answers: answers type. One typed answer per question ID, with literal Choice option inference. -
usage:{ inputTokens: number | undefined; outputTokens: number | undefined; totalTokens: number | undefined; }.inputTokens,outputTokens, andtotalTokens, each possibly undefined. -
warnings:SharedV4Warning[]. Provider warnings, also passed to the SDK warning logger. -
rounding:{ probabilityDecimals?: number; scoreDecimals?: number; } | undefined. Optional provider-declared decimal precision for probabilities and scores. -
providerMetadata:SharedV4ProviderMetadata | undefined. Optional provider-specific metadata. -
response:{ id?: string; timestamp?: Date; modelId?: string; headers?: SharedV4Headers; body?: unknown; } & { timestamp: Date; modelId: string; }. Timestamp, model ID, and optional response ID, headers, and body.
Embedder
-
value:string. The value that was embedded. -
embedding:EmbeddingModelV4Embedding. The embedding of the value. -
usage:EmbeddingModelUsage. The embedding token usage. -
warnings:SharedV4Warning[]. Warnings for the call, e.g. unsupported settings. -
providerMetadata?:SharedV4ProviderMetadata | undefined. Optional provider-specific metadata. -
response?:{ headers?: Record<string, string>; body?: unknown; } | undefined. Optional response data.
EmbedderBatch
-
values:string[]. The values that were embedded. -
embeddings:EmbeddingModelV4Embedding[]. The embeddings. They are in the same order as the values. -
usage:EmbeddingModelUsage. The embedding token usage. -
warnings:SharedV4Warning[]. Warnings for the call, e.g. unsupported settings. -
providerMetadata?:SharedV4ProviderMetadata | undefined. Optional provider-specific metadata. -
responses?:({ headers?: Record<string, string>; body?: unknown; } | undefined)[] | undefined. Optional raw response data.
Reranker
-
originalDocuments:(string | JSONObject)[]. The original documents that were reranked.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
rerankedDocuments:(string | JSONObject)[]. Reranked documents.Sorted by relevance score in descending order.
Can be less than the original documents if there was a topN limit.
An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
ranking:{ originalIndex: number; score: number; document: string | JSONObject; }[]. The ranking is a list of objects with the original index, relevance score, and the reranked document.Sorted by relevance score in descending order.
Can be less than the original documents if there was a topN limit.
An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
providerMetadata?:SharedV4ProviderMetadata | undefined. Optional provider-specific metadata. -
response:{ id?: string; timestamp: Date; modelId: string; headers?: Record<string, string>; body?: unknown; }. Optional raw response data.
ImageGenerator
-
image:GeneratedFile. The first image that was generated.Shape Type Fields Generated file import("ai").GeneratedFileGeneratedFile fields -
images:GeneratedFile[]. The images that were generated.Shape Type Fields Each generated file import("ai").GeneratedFileGeneratedFile fields -
calls:GenerateImageCall[]. The results of the underlying image model calls. -
warnings:SharedV4Warning[]. Warnings for the call, e.g. unsupported settings. -
responses:ImageModelResponseMetadata[]. Response metadata from the provider. There may be multiple responses if we made multiple calls to the model.deprecated: Use
callsto preserve each response with its corresponding images, metadata, warnings, and usage. -
providerMetadata:ImageModelProviderMetadata. Provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific results that can be fully encapsulated in the provider.deprecated: Use the provider metadata in
callsor on individualimagesto preserve its scope. -
usage:ImageModelV4Usage. Combined token usage across all underlying provider calls for this image generation.
transcribe request
-
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific options that are passed through to the provider as body parameters.The outer record is keyed by the provider name, and the inner record is keyed by the provider-specific metadata key.
{ "openai": { "temperature": 0 } }An object keyed by provider name. Each entry contains settings supported by that provider.
-
maxRetries?:number | undefined. Maximum number of retries per transcript model call. Set to 0 to disable retries.default: 2
-
abortSignal?:AbortSignal | undefined. Abort signal. -
headers?:Record<string, string> | undefined. Additional headers to include in the request. Only applicable for HTTP-based providers. -
model:TranscriptionModel. The transcription model to use. -
telemetry?:TelemetryOptions<Context, ToolSet> | undefined. Optional telemetry configuration.Shape Type Fields Value TelemetryTelemetry fields -
download?:((options: { url: URL; abortSignal?: AbortSignal; }) => Promise<{ data: Uint8Array; mediaType: string | undefined; }>) | undefined. Custom download function for fetching audio from URLs. UsecreateDownload()fromaito create a download function with custom size limits.default: createDownload() (2 GiB limit)
-
sourceFormat?:PcmSourceFormat | undefined. Original layout of headerless PCM. Omit for WAV or Web Audio AudioBuffer. Numeric sample arrays supply their encoding.Shape Type Fields Value import("../src/audio/pcm.js").PcmSourceFormatPcmSourceFormat fields -
audio: audio type. Supplied recording as a File, Blob, encoded bytes or base64, or a native URL using the SDK downloader. For an AudioBuffer or described headerless PCM, Casai supplies a WAV.
experimental_streamTranscribe request
-
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific options.An object keyed by provider name. Each entry contains settings supported by that provider.
-
abortSignal?:AbortSignal | undefined. Abort signal. -
headers?:Record<string, string> | undefined. Additional headers to include in the request, if supported by the provider. -
model:TranscriptionModel. The transcription model to use. -
telemetry?:TelemetryOptions<Context, ToolSet> | undefined. Optional telemetry configuration.Shape Type Fields Value TelemetryTelemetry fields -
audio:RawAudio. WAV, AudioBuffer, headerless PCM or raw chunks. Casai prepares samples in the model target format. -
inputAudioFormat:SharedV4AudioFormat. The input audio format for the raw audio chunks.An audio-format object, for example
{ type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported.Shape Type Fields Value import("@ai-sdk/provider").SharedV4AudioFormatAudioFormat fields -
sourceFormat?:PcmSourceFormat | undefined. Original layout of headerless PCM. Omit for WAV or Web Audio AudioBuffer. Numeric sample arrays supply their encoding.Shape Type Fields Value import("../src/audio/pcm.js").PcmSourceFormatPcmSourceFormat fields
experimental_streamTranscribe request
-
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific options.An object keyed by provider name. Each entry contains settings supported by that provider.
-
abortSignal?:AbortSignal | undefined. Abort signal. -
headers?:Record<string, string> | undefined. Additional headers to include in the request, if supported by the provider. -
model:TranscriptionModel. The transcription model to use. -
telemetry?:TelemetryOptions<Context, ToolSet> | undefined. Optional telemetry configuration.Shape Type Fields Value TelemetryTelemetry fields -
includeRawChunks?:boolean | undefined. When true, providers should include raw provider chunks in the stream. -
inputAudioFormat:SharedV4AudioFormat. The input audio format for the raw audio chunks.An audio-format object, for example
{ type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported.Shape Type Fields Value import("@ai-sdk/provider").SharedV4AudioFormatAudioFormat fields -
sourceFormat?:PcmSourceFormat | undefined. Original layout of headerless PCM. Omit for WAV or Web Audio AudioBuffer. Numeric sample arrays supply their encoding.Shape Type Fields Value import("../src/audio/pcm.js").PcmSourceFormatPcmSourceFormat fields -
audio:RawAudio. WAV, AudioBuffer, headerless PCM or raw chunks. Casai prepares samples in the model target format.
transcribe request
-
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific options that are passed through to the provider as body parameters.The outer record is keyed by the provider name, and the inner record is keyed by the provider-specific metadata key.
{ "openai": { "temperature": 0 } }An object keyed by provider name. Each entry contains settings supported by that provider.
-
maxRetries?:number | undefined. Maximum number of retries per transcript model call. Set to 0 to disable retries.default: 2
-
abortSignal?:AbortSignal | undefined. Abort signal. -
headers?:Record<string, string> | undefined. Additional headers to include in the request. Only applicable for HTTP-based providers. -
model:TranscriptionModel. The transcription model to use. -
telemetry?:TelemetryOptions<Context, ToolSet> | undefined. Optional telemetry configuration.Shape Type Fields Value TelemetryTelemetry fields -
sourceFormat?:PcmSourceFormat | undefined. Original layout of headerless PCM. Omit for WAV or Web Audio AudioBuffer. Numeric sample arrays supply their encoding.Shape Type Fields Value import("../src/audio/pcm.js").PcmSourceFormatPcmSourceFormat fields -
audio: audio type. Supplied recording as a File, Blob, encoded bytes or base64, or a native URL using the SDK downloader. For an AudioBuffer or described headerless PCM, Casai supplies a WAV.
Transcriber
-
text:string. The complete transcribed text from the audio. -
segments:{ readonly text: string; readonly startSecond: number; readonly endSecond: number; }[]. Array of transcript segments with timing information. Each segment represents a portion of the transcribed text with start and end times. -
language:string | undefined. The detected language of the audio content, as an ISO-639-1 code (e.g., 'en' for English). May be undefined if the language couldn't be detected. -
durationInSeconds:number | undefined. The total duration of the audio file in seconds. May be undefined if the duration couldn't be determined. -
warnings:SharedV4Warning[]. Warnings for the call, e.g. unsupported settings. -
responses:TranscriptionModelResponseMetadata[]. Response metadata from the provider. There may be multiple responses if we made multiple calls to the model. -
providerMetadata:Record<string, JSONObject>. Provider metadata from the provider.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
TranscriberStream
-
text:PromiseLike<string>. The final transcribed text. -
segments:PromiseLike<{ text: string; startSecond: number; endSecond: number; }[]>. Final transcript segments with timing information, if available. -
language:PromiseLike<string | undefined>. The language of the transcript, if available. -
durationInSeconds:PromiseLike<number | undefined>. The duration of the transcript in seconds, if available. -
warnings:PromiseLike<SharedV4Warning[]>. Warnings for the call, e.g. unsupported settings. -
responses:PromiseLike<TranscriptionModelResponseMetadata[]>. Response metadata. -
providerMetadata:PromiseLike<Record<string, JSONObject>>. Additional provider-specific metadata.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
fullStream:AsyncIterableStream<TranscriptionStreamPart>. Full stream of transcription parts.This is a single-consumer live stream and can only be accessed once. Access it before any result promise when both stream parts and final results are needed; accessing a result promise first consumes the stream internally and makes
fullStreamunavailable.
generateSpeech request
-
text:string. The text to convert to speech. -
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific options that are passed through to the provider as body parameters.The outer record is keyed by the provider name, and the inner record is keyed by the provider-specific metadata key.
{ "openai": {} }An object keyed by provider name. Each entry contains settings supported by that provider.
-
maxRetries?:number | undefined. Maximum number of retries per speech model call. Set to 0 to disable retries.default: 2
-
abortSignal?:AbortSignal | undefined. Abort signal. -
headers?:Record<string, string> | undefined. Additional headers to include in the request. Only applicable for HTTP-based providers. -
instructions?:string | undefined. Instructions for the speech generation e.g. "Speak in a slow and steady tone". -
model:SpeechModel. The speech model to use. -
telemetry?:TelemetryOptions<Context, ToolSet> | undefined. Optional telemetry configuration.Shape Type Fields Value TelemetryTelemetry fields -
voice?:string | undefined. The voice to use for speech generation. -
outputFormat?:(string & {}) | "mp3" | "wav" | undefined. The desired output format for the audio e.g. "mp3", "wav", etc. -
speed?:number | undefined. The speed of the speech generation. -
language?:string | undefined. The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") or "auto" for automatic language detection. Provider support varies.
experimental_streamSpeech request
-
text:string | Iterable<string | SpeechTextPart> | AsyncIterable<string | SpeechTextPart> | ReadableStream<string | SpeechTextPart>. The text to convert to speech: a complete string, or an array, iterable, or stream of text deltas and/or text parts.A text chunk such as
{ type: "text", text: "Hello" }. It can also specify avoiceandproviderOptionsfor that chunk. -
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific options.An object keyed by provider name. Each entry contains settings supported by that provider.
-
abortSignal?:AbortSignal | undefined. Abort signal. -
headers?:Record<string, string> | undefined. Additional headers to include in the request, if supported by the provider. -
instructions?:string | undefined. Instructions for the speech generation e.g. "Speak in a slow and steady tone". -
model:SpeechModel. The speech model to use. -
onError?:((event: { error: unknown; }) => void | PromiseLike<void>) | undefined. Called for each error part the provider reports. Error parts are not fatal:fullStreamincludes them andaudioStreamskips them. The callback is not awaited, and errors it throws are ignored. Defaults to logging the error withconsole.error. -
voice?:string | undefined. The voice to use for speech generation. -
outputFormat?:SharedV4AudioFormat | undefined. The desired format of the output audio chunks, e.g.{ type: 'audio/pcm', rate: 24000 }or{ type: 'audio/mpeg' }. Supported formats are provider-specific.An audio-format object, for example
{ type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported. -
speed?:number | undefined. The speed of the speech generation. -
language?:string | undefined. The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") or "auto" for automatic language detection. Provider support varies.
experimental_streamSpeech request
-
text:string | Iterable<string | SpeechTextPart> | AsyncIterable<string | SpeechTextPart> | ReadableStream<string | SpeechTextPart>. The text to convert to speech: a complete string, or an array, iterable, or stream of text deltas and/or text parts.A text chunk such as
{ type: "text", text: "Hello" }. It can also specify avoiceandproviderOptionsfor that chunk. -
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific options.An object keyed by provider name. Each entry contains settings supported by that provider.
-
abortSignal?:AbortSignal | undefined. Abort signal. -
headers?:Record<string, string> | undefined. Additional headers to include in the request, if supported by the provider. -
instructions?:string | undefined. Instructions for the speech generation e.g. "Speak in a slow and steady tone". -
model:SpeechModel. The speech model to use. -
includeRawChunks?:boolean | undefined. When true, providers should include raw provider chunks in the stream. -
onError?:((event: { error: unknown; }) => void | PromiseLike<void>) | undefined. Called for each error part the provider reports. Error parts are not fatal:fullStreamincludes them andaudioStreamskips them. The callback is not awaited, and errors it throws are ignored. Defaults to logging the error withconsole.error. -
voice?:string | undefined. The voice to use for speech generation. -
outputFormat?:SharedV4AudioFormat | undefined. The desired format of the output audio chunks, e.g.{ type: 'audio/pcm', rate: 24000 }or{ type: 'audio/mpeg' }. Supported formats are provider-specific.An audio-format object, for example
{ type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported. -
speed?:number | undefined. The speed of the speech generation. -
language?:string | undefined. The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") or "auto" for automatic language detection. Provider support varies.
SpeechGenerator
-
audioFormat?:SharedV4AudioFormat | undefined. The actual emitted format on collected streaming speech, including sample rate where applicable; absent on native complete results.An audio-format object, for example
{ type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported.Shape Type Fields Value import("@ai-sdk/provider").SharedV4AudioFormatSpeechAudioFormat fields -
usage?:SpeechModelV4StreamUsage | undefined. Usage information reported for the call, if available. -
audio:GeneratedAudioFile. The generated audio file with the audio data.Shape Type Fields Generated file import("ai").GeneratedAudioFileGeneratedAudioFile fields -
warnings:SharedV4Warning[]. Warnings for the call, e.g. unsupported settings. -
responses:SpeechModelResponseMetadata[]. Response metadata from the provider. There may be multiple responses if we made multiple calls to the model. -
providerMetadata:Record<string, JSONObject>. Provider metadata from the provider.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
SpeechGeneratorStream
-
usage:PromiseLike<SpeechModelV4StreamUsage>. Usage information reported for the call, if available. -
warnings:PromiseLike<SharedV4Warning[]>. Warnings for the call, e.g. unsupported settings. -
responses:PromiseLike<SpeechModelResponseMetadata[]>. Response metadata. -
providerMetadata:PromiseLike<Record<string, JSONObject>>. Additional provider-specific metadata.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
audioStream:AsyncIterableStream<Uint8Array<ArrayBufferLike>>. Stream of audio bytes in generation order.audioStreamandfullStreamshare one live stream: only one of them can be accessed, and only once. Access it before any result promise; accessing a result promise first consumes the stream internally. -
fullStream:AsyncIterableStream<SpeechStreamPart>. Full stream of speech parts (audio, raw, and error parts).audioStreamandfullStreamshare one live stream: only one of them can be accessed, and only once. Access it before any result promise; accessing a result promise first consumes the stream internally.
Translator
-
providerMetadata:Record<string, JSONObject>. Additional provider-specific metadata.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
warnings:SharedV4Warning[]. Warnings for the call, e.g. unsupported settings. -
response:SpeechTranslationModelResponseMetadata. Response metadata. -
usage:SpeechTranslationModelV4Usage | undefined. Usage information for the translation call, if reported by the provider. -
sourceText:string. The final source-language transcript of the input audio. -
translationText:string. The final translated text in the target language.May resolve to an empty string for providers that produce only audio output.
-
durationInSeconds:number | undefined. The duration of the source audio in seconds, if available. -
audio:Uint8Array<ArrayBuffer>. Collected translated audio bytes backed by an ordinary ArrayBuffer. A successful translation with zero audio bytes returns an empty array. The application supplies any media type it knows.
TranslatorStream
-
sourceText:PromiseLike<string>. The final source-language transcript of the input audio. -
translationText:PromiseLike<string>. The final translated text in the target language.May resolve to an empty string for providers that produce only audio output.
-
durationInSeconds:PromiseLike<number | undefined>. The duration of the source audio in seconds, if available. -
usage:PromiseLike<SpeechTranslationModelV4Usage | undefined>. Usage information for the translation call, if reported by the provider. -
warnings:PromiseLike<SharedV4Warning[]>. Warnings for the call, e.g. unsupported settings. -
response:PromiseLike<SpeechTranslationModelResponseMetadata>. Response metadata. -
providerMetadata:PromiseLike<Record<string, JSONObject>>. Additional provider-specific metadata.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
-
fullStream:AsyncIterableStream<TranslationStreamPart>. Full stream of translation parts.This is a single-consumer live stream and can only be accessed once. Access it before any result promise when both stream parts and final results are needed; accessing a result promise first consumes the stream internally and makes
fullStreamunavailable.
VideoGenerator
-
video:GeneratedFile. The first video that was generated.Shape Type Fields First generated video import("ai").GeneratedFileGeneratedFile fields -
videos:GeneratedFile[]. All videos that were generated.Shape Type Fields Each generated video import("ai").GeneratedFileGeneratedFile fields -
warnings:SharedV4Warning[]. Warnings for the call, e.g. unsupported settings. -
responses:VideoModelResponseMetadata[]. Response metadata from the provider. May contain multiple responses if multiple calls were made. -
providerMetadata:SharedV4ProviderMetadata. Provider-specific metadata passed through from the provider.
VoiceAgentClient
-
onError:((error: Error) => void) | undefined. Called when the realtime session encounters an error. -
onToolCall:((args: { toolCall: { toolCallId: string; toolName: string; args: unknown; }; }) => Promise<unknown> | unknown | undefined) | undefined. Turn-based tools only. Return a value to automatically submit it as tool output, or return undefined and call addToolOutput manually later. Live client delegations are application-handled through session metadata and events. -
onEvent:((event: RealtimeServerEvent) => void) | undefined. Called for every normalized realtime server event. -
connect:{ (): Promise<void>; (options: { stream?: MediaStream; capture?: boolean; }): Promise<void>; }. Starts the selected connection. Continuous browser sessions acquire microphone audio by default; capture: false opts out. A supplied Live stream remains caller-owned. The zero-argument overload remains usable as an event handler. -
disconnect:() => void. Immediately releases transports and owned media. Preserves latest usage as unconfirmed unless a terminal provider event was received. -
close:(options?: { eventId?: string; }) => Promise<void>. Wait for final usage when the model supports a session-close acknowledgement. -
sendEvent:(event: RealtimeClientEvent) => Promise<void>. Sends a normalized command in order. Resolves on local serialization/submission, not provider acceptance. Validation can throw synchronously; asynchronous send failures reject and are reported through onError. Live context/results use context-append with a known client delegation ID or null. -
sendTextMessage:(text: string) => void. Turn-based only: sends user text and requests a response. Continuous Live sessions reject this control. The application owns its text conversation and supplies Live context through sendEvent. -
sendAudio:(audio: string) => void. Sends a base64-encoded audio chunk to the provider input audio buffer over WebSocket. WebRTC uses media tracks and rejects JSON audio commands. -
commitAudio:() => void. Turn-based only: commits the provider input audio buffer. -
clearAudioBuffer:() => void. Turn-based only: clears the provider input audio buffer. -
requestResponse:(options?: { modalities?: string[]; }) => void. Turn-based only: requests a new model response. -
cancelResponse:() => void. Turn-based only: cancels the active model response. -
addToolOutput:(callId: string, result: unknown) => void. Turn-based only: submits a tool result back to the realtime provider. Continuous Live sessions reject this control; append application-handled client delegation results with sendEvent instead. -
startAudioCapture:(stream: MediaStream) => void. Starts or replaces capture with the supplied MediaStream. Live paths borrow tracks; the existing legacy capture API retains ownership of its supplied stream. Async attachment failures are reported through onError. -
resumeAudioCapture:() => Promise<void>. Restarts capture, reusing a supplied Live stream or acquiring a fresh SDK-owned microphone. Does not reconnect the provider. -
stopAudioCapture:() => void. Stops local capture and releases SDK-owned microphone tracks. Caller-owned Live tracks are only detached. Does not change the provider input-mute state. -
stopPlayback:() => void. Stops queued model audio playback. -
resumePlayback:() => Promise<void>. Retries browser playback after interruption, suspension, or buffer overflow. Discarded stale audio is not replayed. -
dispose:() => void. Immediately disconnect using native disposal. Unsubscribe application state listeners separately; use close first when graceful completion is required. -
getSnapshot:() => Readonly<import("ai").Experimental_RealtimeState>. Read the current native session state. The snapshot identity is stable between native state changes; treat it and its contents as read-only.Shape Type Fields Returned snapshot Readonly<import("ai").Experimental_RealtimeState>VoiceClientSnapshot fields -
subscribe:(listener: () => void) => () => void. Subscribe to state changes. Returns an unsubscribe function. Read getSnapshot after subscribing for initial rendering; subscribing does not connect or replay events.
VoiceAgentBackend
-
token:string. The ephemeral token value. Used as a Bearer token or in the WebSocket subprotocol header for authentication. -
url:string. The WebSocket URL to connect to. Includes any provider-specific query parameters (e.g. model ID). -
expiresAt?:number | undefined. Unix timestamp (seconds) when this client secret expires. -
tools:RealtimeModelV4ToolDefinition[]. Prepared native tool definitions for this session.Shape Type Fields Each tool definition import("@ai-sdk/provider").Experimental_RealtimeModelV4ToolDefinitionRealtimeToolDefinition fields
VoiceSessionConfig
-
instructions?:string | undefined. System instructions for the model. -
voice?:string | undefined. Voice to use for audio output. -
outputModalities?:("text" | "audio")[] | undefined. Which output modalities the model should produce. -
inputAudioFormat?:SharedV4AudioFormat | undefined. Audio format configuration for input audio.An audio-format object, for example
{ type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported.Shape Type Fields Value import("@ai-sdk/provider").SharedV4AudioFormatAudioFormat fields -
inputAudioTranscription?:{ model?: string; language?: string; prompt?: string; } | undefined. Input audio transcription configuration.When enabled, providers that support input transcription emit normalized
input-transcription-completedevents that can be rendered as user messages.Shape Type Fields Value { model?: string; language?: string; prompt?: string; }SessionTranscription fields -
outputAudioTranscription?:{ model?: string; language?: string; prompt?: string; } | undefined. Output audio transcription configuration.When enabled, providers that support output transcription emit normalized
audio-transcript-delta/audio-transcript-doneevents for the model's spoken response. Some providers transcribe output by default; setting this makes the behavior explicit rather than relying on that default.Shape Type Fields Value { model?: string; language?: string; prompt?: string; }SessionTranscription fields -
outputAudioFormat?:SharedV4AudioFormat | undefined. Audio format configuration for output audio.An audio-format object, for example
{ type: "audio/pcm", rate: 24000 }. The provider determines which formats and sample rates are supported.Shape Type Fields Value import("@ai-sdk/provider").SharedV4AudioFormatAudioFormat fields -
turnDetection?:{ type: "server-vad" | "semantic-vad" | "disabled"; threshold?: number; silenceDurationMs?: number; prefixPaddingMs?: number; } | null | undefined. Voice activity detection configuration. Set to null or type 'disabled' to turn off VAD (push-to-talk mode).Definition:
TurnDetectionShape Type Fields Alternative 1 nullAlternative 2 { type: "server-vad" | "semantic-vad" | "disabled"; threshold?: number; silenceDurationMs?: number; prefixPaddingMs?: number; }TurnDetection fields (2) -
tools?:RealtimeModelV4ToolDefinition[] | undefined. Tool definitions available to the model in this session. -
providerOptions?:Record<string, unknown> | undefined. Provider-specific options that are passed through to the provider.
VoiceWebRTC
-
sessionId:string. The provider identifier for the created session. -
sdp:string. The SDP answer to give to the browser peer connection.
renderOptions fields
-
replayAsyncIterables?:boolean | undefined. Set false to disable automatic async loop replay. Sequential loops close on early exit. Default: true. -
autoescape?:boolean | undefined. Escape HTML-sensitive output characters. Casai defaults standalone rendering to false; AI input preparers always disable it. -
throwOnUndefined?:boolean | undefined. Throw when a template outputs null or undefined. Defaults to false. -
trimBlocks?:boolean | undefined. Remove the first newline after a block tag. Defaults to false. -
lstripBlocks?:boolean | undefined. Remove indentation before a block tag. Defaults to false. -
watch?:boolean | undefined. Cascada configure() loader option. Casai constructs an environment directly, so configure watching on your supplied loader. -
noCache?:boolean | undefined. Cascada configure() loader option. Configure caching on your supplied loader; this flag does not configure it through Casai renderOptions. -
dev?:boolean | undefined. Keep developer-oriented template error details instead of cleaning the stack. Defaults to false. -
web?:{ useCache?: boolean | undefined; async?: boolean | undefined; } | undefined. Cascada configure() web-loader options. With Casai, pass these options to your WebLoader instead.Shape Type Fields WebLoader options { useCache?: boolean | undefined; async?: boolean | undefined; }RenderWeb fields -
express?:object | undefined. Cascada configure() Express integration. Casai does not call configure() or install an Express view engine. -
tags?: tags type. Custom opening and closing delimiters for Cascada template syntax.Shape Type Fields Value RenderTags type RenderTags fields
AudioFormat fields
-
type:string. Audio format type, e.g.audio/pcm,audio/pcmu, oraudio/pcma. -
rate?:number | undefined. Sample rate in Hz. Only applicable for formats that require a rate.
MediaSettings fields
-
track?:number | undefined. A non-negative zero-based absolute container stream index, not the ordinal audio-track number. Omit for the native best audio stream. Missing, non-audio or undecodable selections fail. For a video at index 0 and audio at index 1, select track: 1. This does not select channels within an audio track. -
format?:string | undefined. Optional native input demuxer name. Omit to let FFmpeg detect the container using content and native filename/extension/MIME hints. It is not an output encoding or a model format. Raw input may need an explicit demuxer and native raw-format options. -
options?:Record<string, string | number | bigint | boolean | null | undefined> | undefined. Input AVOptions with native names, scalar values and units. For example headers: "Authorization: Bearer TOKEN\r\n" for an HTTP input. This is not a CLI argument list, output settings or model headers. Native handling determines applicability and may ignore unknown options.
FileAudioTarget fields
-
alternatives?:readonly FileAudioFormat[] | undefined. Additional accepted formats that may be copied; otherwise convert to the primary format.Shape Type Fields Each accepted copy alternative import("../src/audio/preparation.js").FileAudioFormatFileAudioFormat fields -
maxBytes?:number | undefined. Maximum completed encoded file size in bytes, including its container headers. -
maxDurationSeconds?:number | undefined. Maximum selected/encoded audio duration in seconds, including codec padding. -
format:string. Native output container name, such as wav or flac. -
codec:string. Native audio encoder name; also identifies compatible source audio for copying. -
rate?:number | undefined. Required sample rate in Hz; omit to preserve the source rate where the encoder supports it. -
channels?:number | undefined. Required channel count; omit to preserve the source channel layout where supported. -
sampleFormat?:string | undefined. Native sample format name, such as s16 or s32; omit for the encoder's native choice.
_toolOptions fields
-
abortSignal?:AbortSignal | undefined. An optional abort signal that indicates that the overall operation should be aborted. -
experimental_sandbox?:SandboxSession | undefined. The sandbox environment that the tool is operating in. -
toolCallId?:string | undefined. The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data. -
messages?:ModelMessage[] | undefined. Messages that were sent to the language model to initiate the response that contained the tool call. The messages do not include the system prompt nor the assistant response that contained the tool call.A message object with
role(system,user,assistantortool) andcontent. For example:{ role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed.
output fields
-
array: array type. Output specification for array generation. When the model generates a text response, it will return an array of elements.param: element - The schema of the array elements to generate.
param: minItems - Optional minimum number of elements to generate.
param: maxItems - Optional maximum number of elements to generate.
param: name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.
param: description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.
returns: An output specification for generating an array of elements.
Shape Type Fields Builder options { element: import("ai").FlexibleSchema<unknown>; minItems?: number; maxItems?: number; name?: string; description?: string; }OutputArray fields -
choice:<CHOICE extends string>({ options: choiceOptions, name, description }: { options: Array<CHOICE>; name?: string; description?: string; }) => Output<CHOICE, CHOICE, never>. Output specification for choice generation. When the model generates a text response, it will return one of the choice options.param: options - The available choices.
param: name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.
param: description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.
returns: An output specification for generating a choice.
Shape Type Fields Builder options { options: string[]; name?: string; description?: string; }OutputChoice fields -
json:({ name, description }?: { name?: string; description?: string; }) => Output<JSONValue, JSONValue, never>. Output specification for unstructured JSON generation. When the model generates a text response, it will return a JSON object.A JSON value: a string, number, boolean, null, array or object containing other JSON values.
param: name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.
param: description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.
returns: An output specification for generating JSON.
Shape Type Fields Optional builder options { name?: string; description?: string; }OutputJSON fields -
object:<OBJECT>({ schema: inputSchema, name, description }: { schema: FlexibleSchema<OBJECT>; name?: string; description?: string; }) => Output<OBJECT, DeepPartial<OBJECT>, never>. Output specification for typed object generation using schemas. When the model generates a text response, it will return an object that matches the schema.param: schema - The schema of the object to generate.
param: name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.
param: description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.
returns: An output specification for generating objects with the specified schema.
Shape Type Fields Builder options { schema: import("ai").FlexibleSchema<unknown>; name?: string; description?: string; }OutputObject fields -
text:() => Output<string, string, never>. Output specification for text generation. This is the default output mode that generates plain text.returns: An output specification for generating text.
Timeout fields (2)
-
totalMs?:number | undefined. Total time limit for the call, in milliseconds. -
stepMs?:number | undefined. Time limit for a complete step, including generation, retries and local tool execution. -
firstChunkMs?:number | undefined. Streaming time limit until the first content chunk arrives. -
chunkMs?:number | undefined. Streaming time limit between content chunks. -
toolMs?:number | undefined. Default time limit for each tool execution, in milliseconds. -
tools?: tools type. Per-tool time limits that override toolMs. Keys use the tool name followed by Ms, such as lookupOrderMs.
ModelMessage fields (1)
-
role:"system". The message role: system, user, assistant or tool. -
content:string. Content accepted for this role. The type lists supported text and multimodal parts. -
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider.An object keyed by provider name. Each entry contains settings supported by that provider.
ModelMessage fields (2)
-
role:"user". The message role: system, user, assistant or tool. -
content:UserContent. Content accepted for this role. The type lists supported text and multimodal parts. -
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider.An object keyed by provider name. Each entry contains settings supported by that provider.
ModelMessage fields (3)
-
role:"assistant". The message role: system, user, assistant or tool. -
content:AssistantContent. Content accepted for this role. The type lists supported text and multimodal parts. -
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider.An object keyed by provider name. Each entry contains settings supported by that provider.
ModelMessage fields (4)
-
role:"tool". The message role: system, user, assistant or tool. -
content:ToolContent. Content accepted for this role. The type lists supported text and multimodal parts. -
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider.An object keyed by provider name. Each entry contains settings supported by that provider.
ImagePrompt fields
-
images:DataContent[]. Input images for generation or editing. The selected model determines supported formats and editing behavior.Binary data supplied as a base64 string,
Uint8Array,ArrayBuffer, or Node.jsBuffer. -
text?:string | undefined. Text describing the image to generate or edit. -
mask?:DataContent | undefined. An optional mask for editing the supplied images. Mask conventions depend on the selected model.Binary data supplied as a base64 string,
Uint8Array,ArrayBuffer, or Node.jsBuffer.
VideoPrompt fields
-
image:DataContent. Input image for image-to-video generation. Can be a URL string, base64-encoded string, aUint8Array, anArrayBuffer, or aBuffer.Binary data supplied as a base64 string,
Uint8Array,ArrayBuffer, or Node.jsBuffer. -
text?:string | undefined. The text prompt.
Telemetry fields
-
isEnabled?:boolean | undefined. Enable or disable telemetry. Enabled by default when a telemetry integration is registered. Set tofalseto opt out. -
recordInputs?:boolean | undefined. Enable or disable input recording. Enabled by default.You might want to disable input recording to avoid recording sensitive information, to reduce data transfers, or to increase performance.
-
recordOutputs?:boolean | undefined. Enable or disable output recording. Enabled by default.You might want to disable output recording to avoid recording sensitive information, to reduce data transfers, or to increase performance.
-
functionId?:string | undefined. Identifier for this function. Used to group telemetry data by function. -
includeRuntimeContext?:IncludedContext<Context>. Top-level runtime context properties that should be included in telemetry. Runtime context properties are excluded unless they are explicitly set totrue. -
includeToolsContext?:IncludedToolsContext<ToolSet>. Top-level tool context properties that should be included in telemetry, configured per tool.Tool context properties are excluded unless they are explicitly set to
true. -
integrations?:Arrayable<Telemetry>. Per-call telemetry integrations that receive lifecycle events during generation.When provided, these integrations will take precedence over the globally registered integrations for this call.
StreamInclude fields
-
requestBody?:boolean | undefined. Whether to retain the request body in step results. The request body can be large when sending images or files.default: false
-
requestMessages?:boolean | undefined. Whether to retain the request messages in step results. The request messages can be large when sending images or files.default: false
-
rawChunks?:boolean | undefined. Whether to include raw chunks from the provider in the stream.When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider.
This allows access to cutting-edge provider features not yet wrapped by the AI SDK.
default: false
DecisionQuestion fields (1)
-
type:"choice". The question kind. Each kind has its own criteria and instruction requirements. -
instructions?:DecisionModelV4Input | null | undefined. May be omitted or null when supported by the provider and criteria define the judgment. -
criteria:Readonly<Record<string, DecisionModelV4Input | null>>. Nonempty map of option names to descriptions. Null means no description.
DecisionQuestion fields (2)
-
type:"score". The question kind. Each kind has its own criteria and instruction requirements. -
instructions?:DecisionModelV4Input | null | undefined. May be omitted or null when supported by the provider and criteria define the judgment. -
criteria:readonly (DecisionModelV4Input | null)[]. At least one ordered level, indexed from zero. Providers may require more.
DecisionQuestion fields (3)
-
type:"box". The question kind. Each kind has its own criteria and instruction requirements. -
instructions:DecisionModelV4Input. Instructions for this question; whether they may be omitted depends on the question kind.
DecisionQuestion fields (4)
-
type:"boolean". The question kind. Each kind has its own criteria and instruction requirements. -
instructions?:DecisionModelV4Input | null | undefined. May be omitted or null when supported by the provider and criteria define the judgment. -
criteria?:{ readonly true?: DecisionModelV4Input | null; readonly false?: DecisionModelV4Input | null; } | undefined. At least one non-null description is required when instructions are absent.
PcmSourceFormat fields
-
sampleRate:number. Original samples per second per channel. -
channels:number. Original number of interleaved channels. -
encoding?:"pcm_u8" | "pcm_s16le" | "pcm_s24le" | "pcm_s32le" | "pcm_f32le" | "pcm_f64le" | undefined. Required for headerless bytes or stream chunks being converted. A numeric sample array supplies this from its element type.
SpeechTextPart fields
-
type:"text". Identifies a text part. -
text:string. The text to synthesize in this part. -
voice?:string | undefined. The voice that speaks this part (provider-specific, like the call'svoice). Single-voice providers reject a voice that differs from the call's voice. -
providerOptions?:SharedV4ProviderOptions | undefined. Additional provider-specific options for this part.An object keyed by provider name. Each entry contains settings supported by that provider.
VideoFrame fields
-
image:DataContent. The image for this frame.Binary data supplied as a base64 string,
Uint8Array,ArrayBuffer, or Node.jsBuffer. -
frameType:VideoModelV4FrameType. Which frame this image represents.
VideoReference fields
-
data:DataContent. The reference image or video.Binary data supplied as a base64 string,
Uint8Array,ArrayBuffer, or Node.jsBuffer. -
mediaType?:string | undefined. The media type of the reference (e.g. 'image/png', 'video/mp4').
VideoPoll fields
-
intervalMs?:number | undefined. Interval between status checks in milliseconds.default: 5000
-
timeoutMs?:number | undefined. Maximum time to wait for completion in milliseconds.default: 600000 (10 minutes)
-
delay?:((delayInMs: number, options?: { abortSignal?: AbortSignal; }) => PromiseLike<void>) | undefined. Custom delay implementation for polling intervals and webhook timeouts. This can be used with durable workflow sleep functions.default: the built-in timer-based delay
VoiceClientApi fields (1)
token:string. The setup endpoint that returns an Experimental_RealtimeSetupResponse.
VoiceClientApi fields (2)
session:string. Application WebRTC setup endpoint. Accepts JSON { sdp, sessionConfig } and returns JSON { sdp, sessionId }.
VoiceClientApi fields (3)
-
websocket:string. Application-owned raw-protocol relay URL. Use wss in production; never put provider credentials in the URL. -
protocols?:string[] | undefined. Optional relay subprotocols, supported only with websocket.
SessionTranscription fields
-
model?:string | undefined. Provider-specific transcription model. -
language?:string | undefined. Optional language hint for the input audio. -
prompt?:string | undefined. Optional prompt to guide transcription.
TurnDetection fields (2)
-
type:"server-vad" | "semantic-vad" | "disabled". VAD mode. 'server-vad' for automatic detection, 'semantic-vad' for OpenAI's semantic detection, 'disabled' to turn off VAD. -
threshold?:number | undefined. VAD activation threshold (0.0-1.0). Higher values require louder audio to trigger. -
silenceDurationMs?:number | undefined. How long the user must be silent (in ms) before the server ends the turn. -
prefixPaddingMs?:number | undefined. Amount of audio (in ms) to include before the detected start of speech.
resume inputs
-
history:readonly ModelMessage[]. Saved messages for continuation, including tool calls/results and approval events.A message object with
role(system,user,assistantortool) andcontent. For example:{ role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed.Required: Required by resume().
Notes: resume skips source preparation. It does not reconstruct prior per-call settings; supply them again when needed.
-
approve:boolean | readonly string[] | null | undefined. Selects pending approvals when resuming.Notes: Omit to preserve recorded approval decisions. true approves pending requests; false denies them; an ID list approves those requests and denies other pending ones. This belongs only to resume(), not configuration or .run().
generate arguments
-
options:unknown. Application input for Casai context validation. Required exactly when configured public defaults do not satisfy inputSchema. -
prompt?:string | ModelMessage[] | undefined. A prompt. It can be either a text prompt or a list of messages.You can either use
promptormessagesbut not both.A message object with
role(system,user,assistantortool) andcontent. For example:{ role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed. -
messages?:ModelMessage[] | undefined. A list of messages.You can either use
promptormessagesbut not both.A message object with
role(system,user,assistantortool) andcontent. For example:{ role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed. -
abortSignal?:AbortSignal | undefined. Abort signal. -
timeout?:TimeoutConfiguration<{}> | undefined. Timeout in milliseconds. Can be specified as a number or as an object with total, per-step, first-content, inter-content, and tool timeouts. First-content and inter-content timeouts are only enforced by streaming calls.Definition:
TimeoutShape Type Fields Alternative 1 numberAlternative 2 Timeout type Timeout fields (2) -
onStart?:GenerateTextOnStartCallback<{}, Context, Output<any, any, any>> | undefined. Callback that is called when the agent operation begins, before any LLM calls. -
experimental_onStart?:GenerateTextOnStartCallback<{}, Context, Output<any, any, any>> | undefined. Callback that is called when the agent operation begins, before any LLM calls.deprecated: Use
onStartinstead. -
onStepStart?:GenerateTextOnStepStartCallback<{}, Context, Output<any, any, any>> | undefined. Callback that is called when a step (LLM call) begins, before the provider is called. -
experimental_onStepStart?:GenerateTextOnStepStartCallback<{}, Context, Output<any, any, any>> | undefined. Callback that is called when a step (LLM call) begins, before the provider is called.deprecated: Use
onStepStartinstead. -
onToolExecutionStart?:OnToolExecutionStartCallback<{}> | undefined. Callback that is called before each tool execution begins. -
experimental_onToolCallStart?:OnToolExecutionStartCallback<{}> | undefined. Callback that is called before each tool execution begins.deprecated: Use
onToolExecutionStartinstead. -
onToolExecutionEnd?:OnToolExecutionEndCallback<{}> | undefined. Callback that is called after each tool execution completes. -
experimental_onToolCallFinish?:OnToolExecutionEndCallback<{}> | undefined. Callback that is called after each tool execution completes.deprecated: Use
onToolExecutionEndinstead. -
onStepEnd?:GenerateTextOnStepEndCallback<{}, Context> | undefined. Callback that is called when each step (LLM call) ends, including intermediate steps. -
onStepFinish?:GenerateTextOnStepFinishCallback<{}, Context> | undefined. Callback that is called when each step (LLM call) ends, including intermediate steps.deprecated: Use
onStepEndinstead. -
onEnd?:GenerateTextOnEndCallback<{}, Context> | undefined. Callback that is called when all steps are finished and the response is complete. -
onFinish?:GenerateTextOnEndCallback<{}, Context> | undefined. Callback that is called when all steps are finished and the response is complete.deprecated: Use
onEndinstead. -
experimental_sandbox?:SandboxSession | undefined. The sandbox environment that is passed through to tool execution.
stream arguments
-
options:unknown. Application input for Casai context validation. Required exactly when configured public defaults do not satisfy inputSchema. -
prompt?:string | ModelMessage[] | undefined. A prompt. It can be either a text prompt or a list of messages.You can either use
promptormessagesbut not both.A message object with
role(system,user,assistantortool) andcontent. For example:{ role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed. -
messages?:ModelMessage[] | undefined. A list of messages.You can either use
promptormessagesbut not both.A message object with
role(system,user,assistantortool) andcontent. For example:{ role: "user", content: "Hello" }. The role determines which text, image, file and tool parts are allowed. -
abortSignal?:AbortSignal | undefined. Abort signal. -
timeout?:TimeoutConfiguration<ToolSet> | undefined. Timeout in milliseconds. Can be specified as a number or as an object with total, per-step, first-content, inter-content, and tool timeouts. First-content and inter-content timeouts are only enforced by streaming calls.Definition:
TimeoutShape Type Fields Alternative 1 numberAlternative 2 Timeout type Timeout fields (2) -
onStart?:GenerateTextOnStartCallback<ToolSet, Context, Output<any, any, any>> | undefined. Callback that is called when the agent operation begins, before any LLM calls. -
experimental_onStart?:GenerateTextOnStartCallback<ToolSet, Context, Output<any, any, any>> | undefined. Callback that is called when the agent operation begins, before any LLM calls.deprecated: Use
onStartinstead. -
onStepStart?:GenerateTextOnStepStartCallback<ToolSet, Context, Output<any, any, any>> | undefined. Callback that is called when a step (LLM call) begins, before the provider is called. -
experimental_onStepStart?:GenerateTextOnStepStartCallback<ToolSet, Context, Output<any, any, any>> | undefined. Callback that is called when a step (LLM call) begins, before the provider is called.deprecated: Use
onStepStartinstead. -
onToolExecutionStart?:OnToolExecutionStartCallback<ToolSet> | undefined. Callback that is called before each tool execution begins. -
experimental_onToolCallStart?:OnToolExecutionStartCallback<ToolSet> | undefined. Callback that is called before each tool execution begins.deprecated: Use
onToolExecutionStartinstead. -
onToolExecutionEnd?:OnToolExecutionEndCallback<ToolSet> | undefined. Callback that is called after each tool execution completes. -
experimental_onToolCallFinish?:OnToolExecutionEndCallback<ToolSet> | undefined. Callback that is called after each tool execution completes.deprecated: Use
onToolExecutionEndinstead. -
onStepEnd?:GenerateTextOnStepEndCallback<ToolSet, Context> | undefined. Callback that is called when each step (LLM call) ends, including intermediate steps. -
onStepFinish?:GenerateTextOnStepFinishCallback<ToolSet, Context> | undefined. Callback that is called when each step (LLM call) ends, including intermediate steps.deprecated: Use
onStepEndinstead. -
onEnd?:GenerateTextOnEndCallback<ToolSet, Context> | undefined. Callback that is called when all steps are finished and the response is complete. -
onFinish?:GenerateTextOnEndCallback<ToolSet, Context> | undefined. Callback that is called when all steps are finished and the response is complete.deprecated: Use
onEndinstead. -
experimental_sandbox?:SandboxSession | undefined. The sandbox environment that is passed through to tool execution. -
experimental_transform?:Arrayable<StreamTextTransform<ToolSet>>. Optional stream transformations. They are applied in the order they are provided. The stream transformations must maintain the stream structure for streamText to work correctly.
createWebRTCSession inputs
-
sdp:string. The browser’s SDP offer for WebRTC session setup.Required: Required by createWebRTCSession().
executeTool inputs
-
toolCallId:string. The actual ID of the incoming realtime tool call.Required: Required by executeTool().
-
toolName:keyof configured tools. The registered tool to execute.Required: Required by executeTool().
-
args:unknown. The incoming raw tool arguments, validated by the bound tool runner.Required: Required by executeTool().
GeneratedFile fields
-
base64:string. File as a base64 encoded string. -
uint8Array:Uint8Array<ArrayBufferLike>. File as a Uint8Array. -
mediaType:string. The IANA media type of the file. -
providerMetadata?:Record<string, JSONObject> | undefined. Provider-specific metadata for this file.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
GeneratedAudioFile fields
-
format:string. Audio format of the file (e.g., 'mp3', 'wav', etc.) -
base64:string. File as a base64 encoded string. -
uint8Array:Uint8Array<ArrayBufferLike>. File as a Uint8Array. -
mediaType:string. The IANA media type of the file. -
providerMetadata?:Record<string, JSONObject> | undefined. Provider-specific metadata for this file.An object with string keys and JSON values: strings, numbers, booleans, null, arrays or nested JSON objects.
VoiceClientSnapshot fields
-
status:RealtimeStatus. The current connection status. -
messages:UIMessage<unknown, UIDataTypes, UITools>[]. Messages assembled from turn-based response text, transcript, and tool events. Continuous Live transcript fragments are exposed separately through session.transcripts. -
events:RealtimeModelV4ServerEvent[]. Recent normalized provider events for inspection or debug UI. -
isCapturing:boolean. Capture state observed through SDK controls and events on the selected audio track. External changes to borrowed tracks may require an explicit refresh; see Capture ownership. -
isPlaying:boolean. Whether model audio playback is active. -
session?:RealtimeSessionState | undefined. Session lifecycle metadata where supported: sessionId, transcript fragments, client delegation metadata, cumulative voice usage, input mute, terminationReason, and pending/confirmed/unconfirmed finalization. Transcript fragments may overlap or arrive late; they are not complete turns.
RealtimeToolDefinition fields
-
type:"function". The type of the tool (always 'function'). -
name:string. The name of the tool. Unique within the session. -
description?:string | undefined. A description of what the tool does. The model uses this to decide whether to call the tool. -
parameters:JSONSchema7. JSON Schema describing the parameters the tool expects.
RenderWeb fields
-
useCache?:boolean | undefined. Cache resources in a WebLoader. Defaults to false. -
async?:boolean | undefined. Load resources asynchronously in a WebLoader. Use the asynchronous API when enabled.
RenderTags fields
-
blockStart?:string | undefined. Opening block delimiter. Default: {%. -
blockEnd?:string | undefined. Closing block delimiter. Default: %}. -
variableStart?:string | undefined. Opening expression delimiter. Default: {{. -
variableEnd?:string | undefined. Closing expression delimiter. Default: }}. -
commentStart?:string | undefined. Opening comment delimiter. Default: {#. -
commentEnd?:string | undefined. Closing comment delimiter. Default: #}.
FileAudioFormat fields
-
format:string. Native output container name, such as wav or flac. -
codec:string. Native audio encoder name; also identifies compatible source audio for copying. -
rate?:number | undefined. Required sample rate in Hz; omit to preserve the source rate where the encoder supports it. -
channels?:number | undefined. Required channel count; omit to preserve the source channel layout where supported. -
sampleFormat?:string | undefined. Native sample format name, such as s16 or s32; omit for the encoder's native choice.
OutputArray fields
-
element:FlexibleSchema<unknown>. The schema of the array elements to generate. -
minItems?:number | undefined. Optional minimum number of elements to generate. -
maxItems?:number | undefined. Optional maximum number of elements to generate. -
name?:string | undefined. Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. -
description?:string | undefined. Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.
OutputChoice fields
-
options:string[]. The available choices. -
name?:string | undefined. Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. -
description?:string | undefined. Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.
OutputJSON fields
-
name?:string | undefined. Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. -
description?:string | undefined. Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.
OutputObject fields
-
schema:FlexibleSchema<unknown>. The schema of the object to generate. -
name?:string | undefined. Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. -
description?:string | undefined. Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.
Timeout type
{ totalMs?: number; stepMs?: number; firstChunkMs?: number; chunkMs?: number; toolMs?: number; tools?: Partial<Record<`${string}Ms`, number>> | undefined; }
model type
string | EmbeddingModelV4 | EmbeddingModelV3 | EmbeddingModelV2<string> | (string & EmbeddingModelV4) | (string & EmbeddingModelV3) | (string & EmbeddingModelV2<string>) | (EmbeddingModelV4 & string) | (EmbeddingModelV3 & string) | (EmbeddingModelV2<string> & string)
model type
string | ImageModelV4 | ImageModelV3 | ImageModelV2 | (string & ImageModelV4) | (string & ImageModelV3) | (string & ImageModelV2) | (ImageModelV4 & string) | (ImageModelV3 & string) | (ImageModelV2 & string)
model type
string | TranscriptionModelV4 | TranscriptionModelV3 | TranscriptionModelV2 | (string & TranscriptionModelV4) | (string & TranscriptionModelV3) | (string & TranscriptionModelV2) | (TranscriptionModelV4 & string) | (TranscriptionModelV3 & string) | (TranscriptionModelV2 & string)
model type
string | SpeechModelV4 | SpeechModelV3 | SpeechModelV2 | (string & SpeechModelV4) | (string & SpeechModelV3) | (string & SpeechModelV2) | (SpeechModelV4 & string) | (SpeechModelV3 & string) | (SpeechModelV2 & string)
stopWhen type
Arrayable<StopCondition<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>, Record<string, unknown>>>
toolApproval type
ToolApprovalConfiguration<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>, Record<string, unknown>> | undefined
repairToolCall type
ToolCallRepairFunction<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>> | undefined
experimental_refineToolInput type
ToolInputRefinement<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>> | undefined
onStart type
GenerateTextOnStartCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>, NoInfer<Record<string, unknown>>, NoInfer<AIOutput>> | undefined
onStepStart type
GenerateTextOnStepStartCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>, NoInfer<Record<string, unknown>>, NoInfer<AIOutput>> | undefined
onLanguageModelCallEnd type
OnLanguageModelCallEndCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>> | undefined
onToolExecutionStart type
OnToolExecutionStartCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>> | undefined
onToolExecutionEnd type
OnToolExecutionEndCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>> | undefined
onStepEnd type
GenerateTextOnStepEndCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>, NoInfer<Record<string, unknown>>> | undefined
onStepError type
GenerateTextOnStepErrorCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>, NoInfer<Record<string, unknown>>, NoInfer<AIOutput>> | undefined
onEnd type
StreamTextOnEndCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>, NoInfer<Record<string, unknown>>, NoInfer<AIOutput>> | undefined
experimental_transform type
Arrayable<StreamTextTransform<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>>
onChunk type
StreamTextOnChunkCallback<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>> | undefined
onAbort type
StreamTextOnAbortCallback<NoInfer<ResolvedTools<{ [x: string]: ((Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, "execute" | "onInputAvailable" | "onInputStart" | "onInputDelta" | "needsApproval">) | null | undefined; }>>, NoInfer<Record<string, unknown>>> | undefined
DecisionQuestion type
{ readonly type: "choice"; readonly instructions?: import("@ai-sdk/provider").Experimental_DecisionModelV4Input | null; readonly criteria: Readonly<Record<string, import("@ai-sdk/provider").Experimental_DecisionModelV4Input | null>>; }
DecisionQuestion type
{ readonly type: "score"; readonly instructions?: import("@ai-sdk/provider").Experimental_DecisionModelV4Input | null; readonly criteria: readonly (import("@ai-sdk/provider").Experimental_DecisionModelV4Input | null)[]; }
DecisionQuestion type
{ readonly type: "boolean"; readonly instructions?: import("@ai-sdk/provider").Experimental_DecisionModelV4Input | null; readonly criteria?: { readonly true?: import("@ai-sdk/provider").Experimental_DecisionModelV4Input | null; readonly false?: import("@ai-sdk/provider").Experimental_DecisionModelV4Input | null; }; }
size type
`${number}x${number}` | undefined
aspectRatio type
`${number}:${number}` | undefined
aspectRatio type
`${number}:${number}` | "adaptive" | undefined
audio type
(context: PreparedContext) => string | URL | Uint8Array | ArrayBuffer | Blob | File | AudioBuffer | Int16Array | Int32Array | Float32Array | Float64Array | ReadableStream<string | Uint8Array> | PromiseLike<string | URL | Uint8Array | ArrayBuffer | Blob | File | AudioBuffer | Int16Array | Int32Array | Float32Array | Float64Array | ReadableStream<string | Uint8Array>>
audio type
(context: PreparedContext) => Uint8Array | ArrayBuffer | Blob | File | AudioBuffer | Int16Array | Int32Array | Float32Array | Float64Array | ReadableStream<string | Uint8Array> | PromiseLike<Uint8Array | ArrayBuffer | Blob | File | AudioBuffer | Int16Array | Int32Array | Float32Array | Float64Array | ReadableStream<string | Uint8Array>>
text type
(context: PreparedContext) => string | Iterable<string | SpeechTextPart> | AsyncIterable<string | SpeechTextPart> | ReadableStream<string | SpeechTextPart> | PromiseLike<string | Iterable<string | SpeechTextPart> | AsyncIterable<string | SpeechTextPart> | ReadableStream<string | SpeechTextPart>>
api type
{ token: string; session?: never; websocket?: never; protocols?: never; } | { session: string; token?: never; websocket?: never; protocols?: never; } | { websocket: string; protocols?: string[]; token?: never; session?: never; }
staticToolResults type
{ type: "tool-result"; toolCallId: string; toolName: string; input: any; output: any; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: false | undefined; preliminary?: boolean; title?: string; }[]
staticToolResults type
PromiseLike<{ type: "tool-result"; toolCallId: string; toolName: string; input: any; output: any; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: false | undefined; preliminary?: boolean; title?: string; }[]>
answers type
{ [x: string]: { type: "score"; score: number; probabilities?: Record<string, number>; } | { type: "box"; box: { top: number; bottom: number; left: number; right: number; }; } | { type: "boolean"; probability: number; } | { type: "choice"; choice: string; probabilities?: Record<string, number> | undefined; }; }
audio type
string | ArrayBuffer | Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike> | URL | Uint8Array<ArrayBufferLike> | Blob | AudioBuffer | Int16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike> | Float64Array<ArrayBufferLike>
tags type
{ blockStart?: string | undefined; blockEnd?: string | undefined; variableStart?: string | undefined; variableEnd?: string | undefined; commentStart?: string | undefined; commentEnd?: string | undefined; } | undefined
RenderTags type
{ blockStart?: string | undefined; blockEnd?: string | undefined; variableStart?: string | undefined; variableEnd?: string | undefined; commentStart?: string | undefined; commentEnd?: string | undefined; }
array type
<ELEMENT>({ element: inputElementSchema, minItems, maxItems, name, description }: { element: FlexibleSchema<ELEMENT>; minItems?: number; maxItems?: number; name?: string; description?: string; }) => Output<Array<ELEMENT>, Array<ELEMENT>, ELEMENT>
tools type
Partial<Record<`${string}Ms`, number>> | undefined