import { SharedObject, UnavailabilityError } from "expo-modules-core"; import type { GenerateObjectConfig, InferSchema, Schema, SessionConfig, LLMSessionEvents, LLMPrompt, ToolConfig, } from "./ExpoLocalLlm.types"; import ExpoLocalLlmModule from "./ExpoLocalLlmModule"; import { assertAndroidModelSupport, getCapabilities, getModuleDiagnostics, } from "./capabilities"; import { LocalLLMError } from "./errors"; import { parseStructuredOutput, validateSchema, SchemaInvalidError, } from "./validateSchema"; import { generateValidatedObject } from "./validatedOutput"; export class NativeModuleUnavailableError extends UnavailabilityError { constructor(operation: string) { super("ExpoLocalLlm", operation); this.name = "NativeModuleUnavailableError"; this.message = getModuleDiagnostics().message ?? this.message; } } export class LLMSession extends SharedObject { // Methods are implemented natively via the Class() DSL. // TypeScript declarations provide type safety only. respond!: (prompt: LLMPrompt, requestId?: string) => Promise; /** * Streams a response, emitting `token`/`partial` events along the way. * Resolves with the final text when the stream completes, or with the * partial text produced so far if the stream is cancelled via * `cancelStream()`. Rejects if the stream fails. */ streamResponse!: (prompt: LLMPrompt, requestId?: string) => Promise; cancelStream!: () => Promise; /** * Clears the conversation transcript while keeping instructions, tools, * schema, and generation options. Cancels any in-flight stream. Cheap — * the model weights are OS-shared; only the conversation state is rebuilt. */ reset!: () => void; registerTool!: (config: ToolConfig) => void; unregisterTool!: (name: string) => void; resolveToolCall!: (callId: string, result: string) => void; rejectToolCall!: (callId: string, error: string) => void; } export function createLLMSession(config: SessionConfig = {}): LLMSession { if (!ExpoLocalLlmModule) { throw new NativeModuleUnavailableError("createLLMSession"); } assertAndroidModelSupport(config.androidModel); const nativePlatform = require("react-native").Platform; if ( nativePlatform.OS === "android" && config.tools?.length && ExpoLocalLlmModule.getToolCallingVersion?.() !== 1 ) { throw new LocalLLMError( "ERR_TOOL_NOT_SUPPORTED", "Native tool calling is unavailable in this build. Rebuild the app with native tool support." ); } if (config.responseFormat === "json" && !config.schema) { throw new SchemaInvalidError([ { path: "schema", message: "responseFormat 'json' requires a schema", }, ]); } if (config.schema) { const result = validateSchema(config.schema); if (!result.ok) { throw new SchemaInvalidError(result.errors); } } // Strip handler functions before passing to native — native doesn't need them const nativeConfig = { ...config, tools: config.tools?.map(({ handler: _handler, ...rest }) => rest), }; // SAFETY: the native module exposes `LLMSession` as an untyped shared-object // class; its instances implement the `LLMSession` contract in this file. return new ExpoLocalLlmModule.LLMSession(nativeConfig) as LLMSession; } /** * One-shot, stateless generation: creates a session, responds once, and * releases the session. Use this for classification/extraction calls where * conversation history is unwanted — no session bookkeeping, no transcript * accumulation across calls. * * Throws `UnavailabilityError` when the native module is missing; rejects * with the native error when the model is not available. Callers that need * an availability check first can use `ExpoLocalLlmModule.getAvailability()`. */ export async function generate( prompt: LLMPrompt, config: SessionConfig = {} ): Promise { if (config.tools?.length) { throw new LocalLLMError( "ERR_UNSUPPORTED_REQUEST", "generate() does not support tools because one-shot generation cannot service tool-call handlers. Use useLocalLLM() instead." ); } const session = createLLMSession(config); try { return await session.respond(prompt); } finally { session.release(); } } export async function generateObject( prompt: LLMPrompt, config: GenerateObjectConfig ): Promise> { if (config.tools !== undefined) { throw new LocalLLMError( "ERR_UNSUPPORTED_REQUEST", "generateObject() does not support tools. Use useLocalLLM() instead." ); } const { mode = "auto", repairAttempts, signal, ...nativeConfig } = config; if ( (mode !== "auto" && mode !== "constrained" && mode !== "validated") || (repairAttempts !== undefined && repairAttempts !== 0 && repairAttempts !== 1) || (signal !== undefined && !(signal instanceof AbortSignal)) || (mode !== "validated" && (repairAttempts !== undefined || signal !== undefined)) ) { throw new LocalLLMError( "ERR_UNSUPPORTED_REQUEST", "Invalid generateObject options." ); } if (mode === "validated" && signal?.aborted) { const error = new Error("Validated generation was aborted."); error.name = "AbortError"; throw error; } const capabilities = getCapabilities(); const selectedMode = mode === "auto" ? capabilities.objectGenerationMode : mode; if ( !(selectedMode === "validated" ? capabilities.text : capabilities.structuredOutput) ) { if (capabilities.status === "moduleUnavailable") { throw new NativeModuleUnavailableError("generateObject"); } throw new LocalLLMError( "ERR_RESPONSE_FORMAT_NOT_SUPPORTED", `generateObject is unavailable on ${capabilities.platform}.` ); } if (selectedMode === "validated") { return generateValidatedObject( prompt, { ...nativeConfig, mode: "validated", repairAttempts, signal, }, createLLMSession ); } const text = await generate(prompt, { ...nativeConfig, responseFormat: "json", schema: config.schema, }); return parseStructuredOutput(text, config.schema); }