/** Android model selection is explicit; no automatic fallback. Ignored on iOS. */ export type AndroidModel = "default" | "previewFast"; export type ModelReadiness = { availability: ModelAvailability; /** Runtime feature support for the selected model, separate from readiness. */ tools: "available" | "unavailable" | "unknown"; }; export type ModelAvailability = | "available" | "moduleUnavailable" | "notEnabled" | "notReady" | "notEligible" | "downloadRequired" | "downloading" | "unknown"; /** * Stable codes carried by generation failures and the library's own checks, on both platforms. * Branch on these rather than on messages, which come from the OS and change. * Read one from any caught error with `getLocalLLMErrorCode`. */ export type LocalLLMErrorCode = /** The conversation no longer fits the model's context window. Reset or start a new session. */ | "ERR_CONTEXT_WINDOW_EXCEEDED" /** The platform's safety guardrails blocked the prompt or the response. */ | "ERR_GUARDRAIL_VIOLATION" /** The model declined to answer. */ | "ERR_REFUSAL" /** The prompt's language or the device locale is not supported by the model. */ | "ERR_UNSUPPORTED_LANGUAGE" /** The request uses a schema feature or capability the model cannot honour. */ | "ERR_UNSUPPORTED_REQUEST" /** The system is throttling generation (quota, background use, or load). Retry later. */ | "ERR_RATE_LIMITED" /** The model's assets are missing or the device cannot run it right now. */ | "ERR_MODEL_UNAVAILABLE" /** The model's output could not be decoded into the requested structure. */ | "ERR_DECODING_FAILED" /** Generation took longer than the system allows. */ | "ERR_TIMEOUT" /** A tool call failed: the handler threw or timed out, or the hook had no handler for it. */ | "ERR_TOOL_FAILED" /** Any other generation failure. */ | "ERR_GENERATION_FAILED" /** This session already has a generation in progress. */ | "ERR_SESSION_BUSY" /** The session was released or never initialised. */ | "ERR_SESSION_INVALID" /** On-device generation is not available on this OS version. */ | "ERR_NOT_SUPPORTED" /** `responseFormat: "json"` is not supported on this platform. */ | "ERR_RESPONSE_FORMAT_NOT_SUPPORTED" /** Tool calling is not supported on this platform. */ | "ERR_TOOL_NOT_SUPPORTED" /** Android only: downloading Gemini Nano failed. */ | "ERR_MODEL_DOWNLOAD_FAILED" /** An image URI, label, or image count is invalid. */ | "ERR_IMAGE_INVALID" /** The current platform or device model cannot accept image inputs. */ | "ERR_IMAGE_NOT_SUPPORTED" /** The schema passed to a session or `generateObject` is malformed. */ | "ERR_SCHEMA_INVALID" /** The generated JSON did not match the schema. */ | "ERR_STRUCTURED_OUTPUT_INVALID" /** The native module is missing from this build (Expo Go, or not rebuilt). */ | "ERR_UNAVAILABLE"; export type GenerationOptions = { temperature?: number; maxTokens?: number; topK?: number; }; /** A local image supplied with one model request. */ export type ImageInput = { /** A local `file://` URI. */ uri: string; /** A name the prompt can use to refer to this image. */ label: string; }; /** A text-only prompt or a multimodal prompt containing local images. */ export type LLMPrompt = | string | { text: string; /** * Up to eight local images per request on iOS and Android. * Labels must be unique within a request. On iOS, completed images remain * in the session transcript; Android history retains text and tool protocol, without images. */ images?: ImageInput[]; }; // Tool calling types export type ToolParameterType = "string" | "number" | "boolean"; export type ToolParameter = { type: ToolParameterType; description: string; /** Allowed values for a `"string"` parameter. */ enum?: readonly string[]; }; export type ToolParameters = Record; export type InferToolParameter = Parameter extends { type: "string"; enum: readonly (infer Value extends string)[]; } ? Value : Parameter extends { type: "string" } ? string : Parameter extends { type: "number" } ? number : Parameter extends { type: "boolean" } ? boolean : never; /** * Arguments the model supplied for a tool call. On iOS the model's decoding is * constrained to the tool's declared `parameters`, so every declared field is * present with its declared type and enum values are respected. Android validates * the complete native batch against those types and enums before dispatch. Handlers * should still validate values that carry meaning (ranges, formats), as they * would for any other input. */ export type InferToolArguments = { -readonly [Key in keyof Parameters]: InferToolParameter; }; /** Tool arguments when the tool's parameters are not known statically. */ export type ToolArguments = InferToolArguments; /** * A tool the model can call. Declare tools with `defineTool()` to have the * handler's arguments typed from `parameters`. */ export type ToolDefinition = { name: string; description: string; parameters: Parameters; // Method syntax keeps a tool with specific parameters assignable to the // general `ToolDefinition` that `tools` arrays hold. handler(args: InferToolArguments): Promise; }; export type ToolConfig = { name: string; description: string; parameters: ToolParameters; }; export type ToolCallEvent = { requestId?: string; callId: string; toolName: string; arguments: ToolArguments; }; export type ActiveToolCall = { callId: string; toolName: string; }; // Structured output types export type ResponseFormat = "text" | "json"; export type SchemaField = | { type: "string"; description?: string; enum?: readonly string[] } | { type: "number" | "integer" | "boolean"; description?: string } | { type: "array"; description?: string; items: SchemaField } | { type: "object"; description?: string; properties: Record; }; export type Schema = Record; export type InferSchemaField = Field extends { type: "string"; enum: readonly (infer Value extends string)[]; } ? Value : Field extends { type: "string" } ? string : Field extends { type: "number" | "integer" } ? number : Field extends { type: "boolean" } ? boolean : Field extends { type: "array"; items: infer Item extends SchemaField } ? InferSchemaField[] : Field extends { type: "object"; properties: infer Properties extends Schema; } ? InferSchema : never; export type InferSchema = { -readonly [Key in keyof Definition]: InferSchemaField; }; /** * An object still being generated: any field, at any depth, may be missing * until the model reaches it. */ export type DeepPartial = Value extends readonly (infer Item)[] ? DeepPartial[] : Value extends object ? { [Key in keyof Value]?: DeepPartial } : Value; export type GenerateObjectConfig = Omit< SessionConfig, "responseFormat" | "schema" | "tools" > & { schema: Definition; /** One-shot helpers cannot service native tool-call events. */ tools?: never; } & ( | { /** Selects native constraints when available, otherwise validated text generation. */ mode?: "auto"; repairAttempts?: never; signal?: never; } | { mode: "constrained"; repairAttempts?: never; signal?: never } | { /** Text generation followed by JS validation, not constrained decoding. */ mode: "validated"; /** Additional attempts after invalid JSON/schema output. Defaults to 1. */ repairAttempts?: 0 | 1; /** Rejects with Error.name === "AbortError" and releases the session. */ signal?: AbortSignal; } ); export type NativeModuleDiagnostics = | { available: true; reason: null; message: null; setupInstructions: readonly []; } | { available: false; reason: "moduleUnavailable"; message: string; setupInstructions: readonly string[]; }; export type LocalLLMCapabilities = { platform: "ios" | "android" | "unsupported"; backend: "appleFoundationModels" | "geminiNano" | null; status: | "available" | "moduleUnavailable" | "unsupportedOS" | "unsupportedPlatform"; text: boolean; streaming: boolean; /** * iOS reports `supported` when built with Xcode 27+, running on iOS 27+, * and the ready system model advertises vision support. * Android reports `unknown` when the native bridge implements image prompts * and its last cached model availability is `available`; otherwise `unsupported`. * Older native binaries report `unsupported`. The initial cache is `unknown`, so * this starts as `unsupported` until availability has been refreshed. * ML Kit cannot query whether the installed device model accepts images. */ images: "supported" | "unknown" | "unsupported"; /** Integration support. Use getModelReadiness() for selected-model readiness. */ tools: boolean; /** Native constrained output only. Validated and automatic fallback require `text`. */ structuredOutput: boolean; structuredOutputMode: "constrained" | "unsupported"; /** Path selected by the default `generateObject()` mode. */ objectGenerationMode: "constrained" | "validated" | "unsupported"; /** * Integration maturity flag, not hardware-verification status. * False for both supported integrations as of 0.10.0. */ experimental: boolean; }; export type SessionConfig = { androidModel?: AndroidModel; instructions?: string; options?: GenerationOptions; tools?: ToolDefinition[]; toolTimeout?: number; responseFormat?: ResponseFormat; schema?: Schema; includeSchemaInPrompt?: boolean; }; export type TokenEvent = { requestId?: string; /** Incremental text; empty when Android corrects divergent tool-stream callbacks. */ token: string; /** Authoritative full text. Replace displayed text with this value, including corrections. */ accumulated: string; }; export type StreamCompleteEvent = { requestId?: string; text: string; }; export type PartialEvent = { requestId?: string; json: string; complete: boolean; }; export type StreamErrorEvent = { requestId?: string; error: string; code: LocalLLMErrorCode; }; export type DownloadProgress = { androidModel?: AndroidModel; progress: number; }; export type LLMSessionEvents = { token: (event: TokenEvent) => void; partial: (event: PartialEvent) => void; streamComplete: (event: StreamCompleteEvent) => void; streamError: (event: StreamErrorEvent) => void; toolCall: (event: ToolCallEvent) => void; }; export type ExpoLocalLlmModuleEvents = { downloadProgress: (event: DownloadProgress) => void; availabilityChange: (event: { availability: ModelAvailability; androidModel?: AndroidModel; }) => void; };