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 behaviorconfig.transcript?: SerializedTranscript- A transcript saved from an earlier session withsession.transcript. The new session continues that conversation and keeps its instructions. Cannot be combined withinstructions: TypeScript rejects it, and at runtime it throwsINVALID_SESSION_OPTIONS. A transcript that cannot be read throwsINVALID_TRANSCRIPTconfig.tools?: ToolDefinition[]- Array of tools the AI can invokeconfig.useCase?: 'general' | 'contentTagging'- Configures the system model use caseconfig.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 inputoptions?: GenerationOptions- Sampling, temperature, and length limits for this request. SeeGenerationOptionsoptions.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 inputonChunk- Called with the full streamed response so far. Withoptions.schema, called with the partial object generated so faroptions?: GenerationOptions- Sampling, temperature, and length limits for this request. SeeGenerationOptionsoptions.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.objectat the root. It follows the same rules as tool arguments. SeecreateTool. An unsupported schema rejects withSCHEMA_CREATION_ERRORbefore the request reaches the model. Error paths start withresponse, for exampleresponse.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.issuesholds the Zod issues anddetails.responseholds 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.
useLanguageModelanduseStreamingResponsereturn 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
urimust be afile://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 withINVALID_PROMPTbefore the request reaches the model, and so does a file that does not exist. The error message names the image, for exampleimages[0].uri. labelis optional. It names the image so the text can refer to it.- The model needs the
visioncapability. A model without it rejects the request withUNSUPPORTED_CAPABILITY. On iOS 26, a prompt with images rejects withUNSUPPORTED_PLATFORM. - Larger images cost more tokens.
tokenCount,usage, andlastResponseUsageinclude the image tokens. session.transcriptstores 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?: numbermodelFamily?: '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 onlycapabilities?: 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 AIconfig.transcript?: SerializedTranscript- A saved transcript to continue. Cannot be combined withinstructionsconfig.tools?: ToolDefinition[]- Tools the AI can useconfig.onResponse?: (response: string) => void- Callback for responsesconfig.onError?: (error: AppleAIError) => void- Callback for errors
Returns:
session: LanguageModelSession | null- Current session instanceresponse: string- Latest response from the AIloading: boolean- Whether a request is in progresserror: AppleAIError | null- Last error that occurredsend: (prompt: PromptInput, options?: GenerationOptions) => Promise<string>- Function to send messages, with optional per-request generation optionsreset: () => void- Reset response and error stateisSessionReady: 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 textisStreaming: boolean- Whether currently streamingisComplete: boolean- Whether streaming is completeerror: AppleAIError | null- Last error that occurredstreamResponse: (prompt: PromptInput, options?: StreamingOptions) => Promise<string>- Start streamingcancel: () => void- Cancel current streamreset: () => 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 ofinputTokensthe model read from its cache. In a conversation, earlier turns are usually cachedreasoningTokens- The part ofoutputTokensthe model spent on reasoningtotalTokens-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 withDECODING_FAILURE.samplingMode- How the model picks each token.greedyalways picks the most likely token.randomTopKsamples from thetopmost likely tokens (topis an integer of 1 or more).randomProbabilityThresholdsamples from the smallest set of tokens whose probabilities add up toprobabilityThreshold(greater than 0, at most 1).seedis 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. Withrequired, the model calls a tool at every step, so the request can fail to end. Preferallowedunless 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 thereasoningcapability (for exampleAFM 3 Core) rejects the request withUNSUPPORTED_CAPABILITY. CheckcheckFoundationModelsAvailability().capabilitiesfirst.
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
| Code | Meaning |
|---|---|
ARGUMENT_PARSING_ERROR | The tool arguments from the model could not be parsed |
ASSETS_UNAVAILABLE | Model assets are not available |
CONTEXT_EXCEEDED | The conversation exceeded the context window. The session was recreated with a summary. Retry the request |
CONTEXT_RECOVERY_FAILED | The context window was exceeded and the session could not be recreated |
DECODING_FAILURE | The model response could not be decoded |
GENERATION_ERROR | The model failed with an error this library does not know yet, for example one added in a new OS version |
GUARDRAIL_VIOLATION | The prompt or response violated the model guardrails |
INVALID_GENERATION_OPTIONS | A GenerationOptions value is invalid. details.field names the field |
INVALID_PROMPT | A prompt image is not a file:// URI or its file does not exist. The message names the image |
INVALID_SESSION_OPTIONS | The session options combine instructions and transcript |
INVALID_TRANSCRIPT | The 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_UNAVAILABLE | Apple Intelligence is not available on this device |
PREWARM_ERROR | prewarm failed |
RATE_LIMITED | The model rate-limited the request |
REFUSAL | The model refused the request |
RESPONSE_PARSING_ERROR | A tool handler returned a value that could not be converted |
RESPONSE_VALIDATION_ERROR | A structured response does not match its schema. details.issues holds the Zod issues |
SCHEMA_CREATION_ERROR | A tool or response schema uses a feature the model does not support |
SESSION_BUSY | Another request is in progress on this session |
SESSION_INITIALIZATION_ERROR | The native session could not be created for a reason with no specific code |
SESSION_NOT_INITIALIZED | useLanguageModel has no session yet |
SESSION_RESPONSE_ERROR | respond failed for a reason with no specific code |
SESSION_STREAMING_ERROR | streamResponse failed for a reason with no specific code |
STREAM_CALLBACK_ERROR | The onChunk callback threw. details.causeCode holds the code of the thrown error |
TIMEOUT | The request timed out (iOS 27+) |
TOKEN_COUNT_ERROR | Token counting failed |
TOOL_CALL_ERROR | A tool call failed |
TOOL_EXECUTION_ERROR | A tool handler threw |
TRANSCRIPT_ENCODING_ERROR | session.transcript could not encode the conversation |
TRANSCRIPT_MUTATION_WHILE_RESPONDING | The session transcript changed while the model was responding (iOS 27+) |
UNKNOWN_ERROR | A failure with no code and no operation to attribute it to |
UNKNOWN_TOOL_ERROR | The model called a tool the session does not have |
UNSUPPORTED_CAPABILITY | The model does not support a capability the request needs, such as reasoningLevel or image input (iOS 27+) |
UNSUPPORTED_GUIDE | The request used an unsupported generation guide |
UNSUPPORTED_LANGUAGE_OR_LOCALE | The request used an unsupported language or locale |
UNSUPPORTED_PLATFORM | The OS version does not support the call |
UNSUPPORTED_TRANSCRIPT_CONTENT | The 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()andz.array(), nested to any depth.optional(),.nullish(), and.default()— the field becomes optional for the modelz.enum([...])and stringz.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