Skip to main content

API Reference

LanguageModelSession​

Constructor​

Creates a new LanguageModelSession instance. Throws an error if Apple Intelligence is not available.

constructor(config?: LanguageModelSessionOptions)

Parameters:

  • config.instructions?: string - System instructions defining AI behavior
  • config.transcript?: SerializedTranscript - A transcript saved from an earlier session with session.transcript. The new session continues that conversation and keeps its instructions. Cannot be combined with instructions: TypeScript rejects it, and at runtime it throws INVALID_SESSION_OPTIONS. A transcript that cannot be read throws INVALID_TRANSCRIPT
  • config.tools?: ToolDefinition[] - Array of tools the AI can invoke
  • config.useCase?: 'general' | 'contentTagging' - Configures the system model use case
  • config.guardrails?: 'default' | 'permissiveContentTransformations' - Configures Foundation Models guardrails

Instance Methods​

respond(prompt, options?)​

Generates a complete response from the language model.

respond(prompt: PromptInput, options?: GenerationOptions): Promise<string>
respond<S extends ObjectSchema>(
prompt: PromptInput,
options: StructuredGenerationOptions<S>,
): Promise<z.infer<S>>

Parameters:

  • prompt: PromptInput - The user's message, as text or as text with images. See Image input
  • options?: GenerationOptions - Sampling, temperature, and length limits for this request. See GenerationOptions
  • options.schema?: ObjectSchema - A Zod object schema. When set, the response is constrained to the schema and the promise resolves with the parsed value. See Structured output
const answer = await session.respond('Name a color', {
samplingMode: { kind: 'greedy' },
maximumResponseTokens: 20,
});

streamResponse(prompt, callback, options?)​

Initiates a streaming response from the language model.

streamResponse(
prompt: PromptInput,
onChunk: (responseSoFar: string) => void,
options?: GenerationOptions,
): Promise<string>
streamResponse<S extends ObjectSchema>(
prompt: PromptInput,
onChunk: (partial: DeepPartial<z.input<S>>) => void,
options: StructuredGenerationOptions<S>,
): Promise<z.infer<S>>

Parameters:

  • prompt: PromptInput - The user's message, as text or as text with images. See Image input
  • onChunk - Called with the full streamed response so far. With options.schema, called with the partial object generated so far
  • options?: GenerationOptions - Sampling, temperature, and length limits for this request. See GenerationOptions
  • options.schema?: ObjectSchema - A Zod object schema. See Structured output

Structured output​

const Contact = z.object({
name: z.string(),
role: z.enum(['engineer', 'designer', 'manager']),
address: z.object({ city: z.string(), country: z.string() }),
skills: z.array(z.string()).max(4),
});

const contact = await session.respond(text, { schema: Contact });

const final = await session.streamResponse(text, setDraft, { schema: Contact });
  • The schema must have z.object at the root. It follows the same rules as tool arguments. See createTool. An unsupported schema rejects with SCHEMA_CREATION_ERROR before the request reaches the model. Error paths start with response, for example response.address.city.
  • The final value is parsed with the schema, so defaults and transforms apply. If it does not parse, the request rejects with RESPONSE_VALIDATION_ERROR. details.issues holds the Zod issues and details.response holds the raw value. This can happen with checks the model cannot see, such as .refine().
  • Each streamed snapshot is the complete object generated so far, as valid JSON. Snapshots are not validated. Fields appear in the order the model writes them, which is not always the schema order. A string can be incomplete. An enum value can be '' before the model picks one. An array can hold an empty placeholder element ({} or '') before the model fills it in. Consecutive snapshots can be equal.
  • Context overflow and the other generation errors have the same codes as for text responses.
  • useLanguageModel and useStreamingResponse return text only.

Image input​

On iOS 27 and later, a prompt can carry images. Pass an object with text and images instead of a string. It works with respond, streamResponse, tokenCount, structured output, and the hooks.

const Receipt = z.object({ merchant: z.string(), total: z.number() });

const { capabilities } = checkFoundationModelsAvailability();
if (capabilities?.includes('vision')) {
const receipt = await session.respond(
{
text: 'What is on this receipt?',
images: [{ uri: 'file:///path/to/receipt.jpg', label: 'receipt' }],
},
{ schema: Receipt },
);
}
  • Each uri must be a file:// URI to an image on the device. Remote URLs and photo library (ph://) URIs are not supported, so download or export the image to a file first. Any other URI rejects with INVALID_PROMPT before the request reaches the model, and so does a file that does not exist. The error message names the image, for example images[0].uri.
  • label is optional. It names the image so the text can refer to it.
  • The model needs the vision capability. A model without it rejects the request with UNSUPPORTED_CAPABILITY. On iOS 26, a prompt with images rejects with UNSUPPORTED_PLATFORM.
  • Larger images cost more tokens. tokenCount, usage, and lastResponseUsage include the image tokens.
  • session.transcript stores each image inside the transcript, so a saved transcript grows by more than the image file's size.
  • Tools cannot receive the images yet.

tokenCount(prompt)​

Returns the number of tokens the provided prompt consumes for this session's model. On iOS 27 and later the count includes the prompt's images.

tokenCount(prompt: PromptInput): Promise<number>

Parameters:

  • prompt: PromptInput - The prompt to measure. See Image input

Availability: iOS 26.4 or later. On earlier versions the returned promise rejects with an UNSUPPORTED_PLATFORM error.

prewarm(promptPrefix?)​

Asks the system to load the model resources for this session before the first request, so the first response can start sooner. Call it when a request is likely soon, such as when a chat screen opens.

prewarm(promptPrefix?: string): void

Parameters:

  • promptPrefix?: string - The expected start of the next prompt, when known

A native failure throws PREWARM_ERROR.

Instance Properties​

wasContextReset​

Boolean flag indicating whether the session's context was automatically summarized and reset after reaching the model's context limit. Useful for informing the user that earlier turns may no longer be in context.

readonly wasContextReset: boolean

usage​

Tokens used by every completed request in this session. iOS 27 and later only. undefined on iOS 26.

readonly usage: TokenUsage | undefined

The count includes the summary request of a context overflow reset, so it does not go down when the session is replaced. A session restored from a transcript starts again from zero.

lastResponseUsage​

Tokens used by the latest respond or streamResponse call. iOS 27 and later only. undefined on iOS 26, before the first request, and after a request that failed.

readonly lastResponseUsage: TokenUsage | undefined

inputTokens covers the whole conversation the model read for this request, including instructions and tool definitions. inputTokens + outputTokens is therefore how much of the context window the session fills after the request.

When the model calls tools, a request has more than one model pass. lastResponseUsage counts only the final pass that wrote the answer, and usage counts every pass, so after a tool call usage grows by more than lastResponseUsage.

await session.respond('Plan a 3 day trip');
session.lastResponseUsage; // { inputTokens, cachedInputTokens, outputTokens, reasoningTokens, totalTokens }
await session.respond('Make it 2 days');
session.usage?.totalTokens; // both requests together

transcript​

The conversation so far, including the instructions. Each read returns the current state. After a context overflow the session is replaced by a summarized one, and transcript reads the replacement.

readonly transcript: SerializedTranscript
await storage.set('chat', session.transcript);

const saved = (await storage.get('chat')) as SerializedTranscript;
const restored = new LanguageModelSession({ transcript: saved, tools });

Tools are not stored in the transcript. Pass them again to the new session. A transcript that cannot be encoded throws TRANSCRIPT_ENCODING_ERROR.

Functions​

checkFoundationModelsAvailability()​

Check if Apple Intelligence is available on the device.

function checkFoundationModelsAvailability(): FoundationModelsAvailability

Returns: Availability status object with isAvailable, status, and message.

The returned object also includes:

  • contextSize?: number
  • modelFamily?: '26.0-26.3' | '26.4+' (deprecated, see below)
  • variant?: string - The display name of the on-device model, for example 'AFM 3 Core'. iOS 27 and later only
  • capabilities?: ModelCapability[] - The features the on-device model supports. iOS 27 and later only
checkFoundationModelsAvailability();
// { isAvailable: true, status: 'available', ..., variant: 'AFM 3 Core', capabilities: ['vision', 'guidedGeneration', 'toolCalling'] }

The model differs between devices. Check capabilities before you use a feature that not every model has, such as reasoningLevel.

getFoundationModelsModelFamily()​

Deprecated. The value is guessed from the iOS version, and every iOS 27 model reports '26.4+'. On iOS 27 and later, read variant from checkFoundationModelsAvailability(). iOS 26 does not report a model name, so the guess stays for iOS 26.

function getFoundationModelsModelFamily(): '26.0-26.3' | '26.4+' | undefined

getFoundationModelsContextSize()​

function getFoundationModelsContextSize(): number | undefined

On iOS 26.4 or later this is bridged directly to the native SystemLanguageModel.contextSize. On iOS 26.0 through 26.3 (where the native API is unavailable) it returns undefined; Apple documents a 4,096-token context window for that model family.

Hooks​

useLanguageModel(config?)​

React hook for managing language model sessions with automatic lifecycle management.

function useLanguageModel(config?: UseLanguageModelConfig): UseLanguageModelReturn

Parameters:

  • config.instructions?: string - System instructions for the AI
  • config.transcript?: SerializedTranscript - A saved transcript to continue. Cannot be combined with instructions
  • config.tools?: ToolDefinition[] - Tools the AI can use
  • config.onResponse?: (response: string) => void - Callback for responses
  • config.onError?: (error: AppleAIError) => void - Callback for errors

Returns:

  • session: LanguageModelSession | null - Current session instance
  • response: string - Latest response from the AI
  • loading: boolean - Whether a request is in progress
  • error: AppleAIError | null - Last error that occurred
  • send: (prompt: PromptInput, options?: GenerationOptions) => Promise<string> - Function to send messages, with optional per-request generation options
  • reset: () => void - Reset response and error state
  • isSessionReady: boolean - Whether session is initialized and ready

useStreamingResponse(session)​

Lower-level hook for streaming AI responses with more control.

function useStreamingResponse(session: LanguageModelSession): UseStreamingResponseReturn

Parameters:

  • session: LanguageModelSession - The session to use for streaming

Returns:

  • response: string - Current response text
  • isStreaming: boolean - Whether currently streaming
  • isComplete: boolean - Whether streaming is complete
  • error: AppleAIError | null - Last error that occurred
  • streamResponse: (prompt: PromptInput, options?: StreamingOptions) => Promise<string> - Start streaming
  • cancel: () => void - Cancel current stream
  • reset: () => void - Reset state

Types​

FoundationModelsAvailability​

interface FoundationModelsAvailability {
isAvailable: boolean;
status: AvailabilityStatus;
message: string;
contextSize?: number;
/** @deprecated */
modelFamily?: '26.0-26.3' | '26.4+';
variant?: string;
capabilities?: ModelCapability[];
}

type ModelCapability = 'vision' | 'guidedGeneration' | 'reasoning' | 'toolCalling';

PromptInput​

type PromptInput = string | { text: string; images?: PromptImage[] };

interface PromptImage {
uri: string;
label?: string;
}

See Image input.

TokenUsage​

Token counts that Apple reports for requests. iOS 27 and later only.

interface TokenUsage {
inputTokens: number;
cachedInputTokens: number;
outputTokens: number;
reasoningTokens: number;
totalTokens: number;
}
  • cachedInputTokens - The part of inputTokens the model read from its cache. In a conversation, earlier turns are usually cached
  • reasoningTokens - The part of outputTokens the model spent on reasoning
  • totalTokens - inputTokens + outputTokens

AvailabilityStatus​

type AvailabilityStatus =
| 'available'
| 'unavailable.platformNotSupported'
| 'unavailable.deviceNotEligible'
| 'unavailable.appleIntelligenceNotEnabled'
| 'unavailable.modelNotReady'
| 'unavailable.unknown'

GenerationOptions​

Options for one respond or streamResponse request. All fields are optional. Invalid values reject the request with an INVALID_GENERATION_OPTIONS error before it reaches the model. The error's details.field names the invalid field.

interface GenerationOptions {
temperature?: number;
maximumResponseTokens?: number;
samplingMode?: SamplingMode;
toolCallingMode?: ToolCallingMode;
reasoningLevel?: ReasoningLevel;
}

type SamplingMode =
| { kind: 'greedy' }
| { kind: 'randomTopK'; top: number; seed?: number }
| { kind: 'randomProbabilityThreshold'; probabilityThreshold: number; seed?: number };

type ToolCallingMode = 'allowed' | 'required' | 'disallowed';

type ReasoningLevel = 'light' | 'moderate' | 'deep';
  • temperature - A number from 0 to 1 inclusive. Lower values give more predictable output.
  • maximumResponseTokens - A positive integer. The response stops at this many tokens. In a session with tools, a very small value (for example 5) can reject with DECODING_FAILURE.
  • samplingMode - How the model picks each token. greedy always picks the most likely token. randomTopK samples from the top most likely tokens (top is an integer of 1 or more). randomProbabilityThreshold samples from the smallest set of tokens whose probabilities add up to probabilityThreshold (greater than 0, at most 1). seed is an optional non-negative integer that makes random sampling repeatable.
  • toolCallingMode - Whether the model may (allowed), must (required), or must not (disallowed) call tools. iOS 27 and later only. iOS 26 ignores it. With required, the model calls a tool at every step, so the request can fail to end. Prefer allowed unless your tool loop has an exit.
  • reasoningLevel - How much the model reasons before it answers. iOS 27 and later only. iOS 26 ignores it. A model without the reasoning capability (for example AFM 3 Core) rejects the request with UNSUPPORTED_CAPABILITY. Check checkFoundationModelsAvailability().capabilities first.

StructuredGenerationOptions​

type ObjectSchema = z.ZodObject;

interface StructuredGenerationOptions<S extends ObjectSchema> extends GenerationOptions {
schema: S;
}

DeepPartial​

The type of a streamed partial object. Every field is optional, and every string type (including enums and literals) widens to string, because a partial value can be incomplete.

type DeepPartial<T> = T extends string
? string
: T extends readonly (infer Element)[]
? DeepPartial<Element>[]
: T extends object
? { [Key in keyof T]?: DeepPartial<T[Key]> }
: T;

LanguageModelSessionOptions​

type LanguageModelSessionOptions = {
tools?: ToolDefinition[];
useCase?: 'general' | 'contentTagging';
guardrails?: 'default' | 'permissiveContentTransformations';
} & (
| { instructions?: string; transcript?: never }
| { transcript: SerializedTranscript; instructions?: never }
);

SerializedTranscript​

A session transcript in Apple's Transcript JSON format, typed as a branded string.

type SerializedTranscript = string & { readonly [brand]: 'SerializedTranscript' };

The format belongs to Apple and carries a version ("version":"1.1" on iOS 27). The only promise is that a value read from session.transcript restores through new LanguageModelSession({ transcript }). Do not build or edit one by hand. A value read back from storage needs a cast: stored as SerializedTranscript.

The decoder rejects versions, entry roles, and segment types it does not know. On iOS 27 it rejects every version other than 1.1. A transcript that holds iOS 27-only content, such as reasoning entries or attachment segments, is therefore not expected to restore on iOS 26. Treat INVALID_TRANSCRIPT as a normal outcome after an OS update, and start a new session when it occurs.

ToolDefinition​

interface ToolDefinition {
name: string;
description: string;
arguments: AnyMap;
handler: (args: AnyMap) => Promise<AnyMap>;
}

AppleAIError​

class AppleAIError extends Error {
readonly code: string;
readonly details?: Record<string, any>;

constructor(code: string, message: string, details?: Record<string, any>);
static fromErrorInfo(errorInfo: AppleAIErrorInfo): AppleAIError;
toErrorInfo(): AppleAIErrorInfo;
}

Error Codes​

CodeMeaning
ARGUMENT_PARSING_ERRORThe tool arguments from the model could not be parsed
ASSETS_UNAVAILABLEModel assets are not available
CONTEXT_EXCEEDEDThe conversation exceeded the context window. The session was recreated with a summary. Retry the request
CONTEXT_RECOVERY_FAILEDThe context window was exceeded and the session could not be recreated
DECODING_FAILUREThe model response could not be decoded
GENERATION_ERRORThe model failed with an error this library does not know yet, for example one added in a new OS version
GUARDRAIL_VIOLATIONThe prompt or response violated the model guardrails
INVALID_GENERATION_OPTIONSA GenerationOptions value is invalid. details.field names the field
INVALID_PROMPTA prompt image is not a file:// URI or its file does not exist. The message names the image
INVALID_SESSION_OPTIONSThe session options combine instructions and transcript
INVALID_TRANSCRIPTThe transcript option cannot be decoded. It is not valid JSON, not a transcript, or holds a version or content this OS does not know
MODEL_UNAVAILABLEApple Intelligence is not available on this device
PREWARM_ERRORprewarm failed
RATE_LIMITEDThe model rate-limited the request
REFUSALThe model refused the request
RESPONSE_PARSING_ERRORA tool handler returned a value that could not be converted
RESPONSE_VALIDATION_ERRORA structured response does not match its schema. details.issues holds the Zod issues
SCHEMA_CREATION_ERRORA tool or response schema uses a feature the model does not support
SESSION_BUSYAnother request is in progress on this session
SESSION_INITIALIZATION_ERRORThe native session could not be created for a reason with no specific code
SESSION_NOT_INITIALIZEDuseLanguageModel has no session yet
SESSION_RESPONSE_ERRORrespond failed for a reason with no specific code
SESSION_STREAMING_ERRORstreamResponse failed for a reason with no specific code
STREAM_CALLBACK_ERRORThe onChunk callback threw. details.causeCode holds the code of the thrown error
TIMEOUTThe request timed out (iOS 27+)
TOKEN_COUNT_ERRORToken counting failed
TOOL_CALL_ERRORA tool call failed
TOOL_EXECUTION_ERRORA tool handler threw
TRANSCRIPT_ENCODING_ERRORsession.transcript could not encode the conversation
TRANSCRIPT_MUTATION_WHILE_RESPONDINGThe session transcript changed while the model was responding (iOS 27+)
UNKNOWN_ERRORA failure with no code and no operation to attribute it to
UNKNOWN_TOOL_ERRORThe model called a tool the session does not have
UNSUPPORTED_CAPABILITYThe model does not support a capability the request needs, such as reasoningLevel or image input (iOS 27+)
UNSUPPORTED_GUIDEThe request used an unsupported generation guide
UNSUPPORTED_LANGUAGE_OR_LOCALEThe request used an unsupported language or locale
UNSUPPORTED_PLATFORMThe OS version does not support the call
UNSUPPORTED_TRANSCRIPT_CONTENTThe session transcript has content the model does not support (iOS 27+)

The same failure has the same code on iOS 26 and iOS 27.

StreamingOptions​

interface StreamingOptions extends GenerationOptions {
onToken?: (token: string) => void;
onComplete?: (fullResponse: string) => void;
onError?: (error: AppleAIError) => void;
}

The generation fields apply to that stream. The callbacks are not sent to the model.

Utilities​

createTool(definition)​

Helper function to create type-safe tools with Zod schema validation.

function createTool<T extends ObjectSchema>(definition: {
name: string;
description: string;
arguments: T;
handler: (params: z.infer<T>) => Promise<AnyMap>;
}): ToolDefinition

The Zod schema you pass is the exact contract the model sees. The same rules apply to the schema of a structured response. Supported schema features:

  • z.string(), z.number(), z.number().int(), z.boolean()
  • z.object() and z.array(), nested to any depth
  • .optional(), .nullish(), and .default() — the field becomes optional for the model
  • z.enum([...]) and string z.literal()
  • Inclusive bounds: .min() / .max() on numbers and arrays
  • .describe() on any field

Unsupported features fail at createTool time with a SCHEMA_CREATION_ERROR that names the property and a supported alternative. Rejected: bare .nullable() on a required field (the model cannot emit null; use .nullish()), unions, records, tuples, intersections, non-string enums and literals, regex patterns and string formats (.email() and similar), exclusive bounds (.gt() / .lt()), and .multipleOf().

Tool arguments and results round-trip with full structure: nested objects, arrays, and null values are preserved in both directions.

If you construct a ToolDefinition by hand instead of using createTool, the arguments field accepts either a JSON Schema document (as described above) or a legacy flat map of { propertyName: "string" | "number" | "integer" | "boolean" }. Unknown type names in the flat map fail with a SCHEMA_CREATION_ERROR.

isAppleAIError(error)​

Type guard to check if an error is an AppleAIError.

function isAppleAIError(error: any): error is AppleAIError

parseNativeError(error)​

Parse native errors into AppleAIError instances.

function parseNativeError(error: any): AppleAIError