DEV Community

Cover image for On-Device AI in React Native & Expo
pielouNW
pielouNW

Posted on

On-Device AI in React Native & Expo

In this Expo & React Native tutorial, you’ll learn how to run a large language model (LLM) directly on a user’s device: no server, no API key needed. We’ll start from scratch with a simple chat exchange, and progressively introduce more advanced features: multimodal input, speech-to-text, text-to-speech, voice activity detection, tool calling and RAG.

Each concept is explained before the code, so you can follow along whether you're new to on-device AI.


Why run AI On-Device?

Most AI features rely on a cloud API: you send a request to a remote server, it runs the model, and sends a response back. That works well, but it comes with tradeoffs.

Running the model directly on the device avoids all of them:

  • Works offline — no internet connection required
  • Privacy by design — user data never leaves the device
  • Low latency — no network round-trip
  • No cloud costs — inference is free

The tradeoff is raw capability: on-device models are smaller and less powerful than frontier cloud models. But for many use cases like summarization, chatbots, or local search, they're more than good enough.


About NobodyWho

We'll use the NobodyWho library throughout this tutorial. It wraps llama.cpp in Rust and exposes a clean React Native API for running locally any model in .gguf format.

Install it with npm install react-native-nobodywho or npx expo install react-native-nobodywho for Expo.


Loading a Model

NobodyWho can download a GGUF model for you directly from Hugging Face, cache it, and reuse it on every subsequent launch. That means you don't need to bundle anything into your app or manage downloads yourself:

import { Chat } from "react-native-nobodywho";

const chat = await Chat.fromPath({
  modelPath: "huggingface:NobodyWho/Qwen_Qwen3-0.6B-GGUF/Qwen_Qwen3-0.6B-Q4_K_M.gguf",
});
Enter fullscreen mode Exit fullscreen mode

The first time this runs, the model is downloaded to the app’s cache directory. Every call after that loads the model directly.

modelPath accepts a few different forms:

Form Example Notes
HuggingFace reference hf:owner/repo/file.gguf Downloaded and cached on first use
HTTPS URL https://example.com/model.gguf Downloaded and cached on first use
Local path ./model.gguf Used as-is, no download

The HuggingFace prefix is case-insensitive and the // is optional, so hf:, hf://, huggingface:, and huggingface:// are all equivalent. You can also pass "auto" to let NobodyWho pick a chat model based on the device's available memory, which is a handy default if you don't want to think about model selection at all.

You can track a remote download by passing onDownloadProgress to Chat.fromPath:

const chat = await Chat.fromPath({
  modelPath: "huggingface:NobodyWho/Qwen_Qwen3-0.6B-GGUF/Qwen_Qwen3-0.6B-Q4_K_M.gguf",
  onDownloadProgress: (downloaded, total) => {
    console.log(`${downloaded} / ${total} bytes`);
  },
});
Enter fullscreen mode Exit fullscreen mode

You can find thousands of LLMs in .gguf format on Hugging Face here.


Basic Chat

With a model loaded, you're ready to start a conversation:

const chat = await Chat.fromPath({
  modelPath: "huggingface:NobodyWho/Qwen_Qwen3-0.6B-GGUF/Qwen_Qwen3-0.6B-Q4_K_M.gguf",
});
const response = await chat.ask("Is water wet?").completed();
console.log(response); // Yes, indeed, water is wet!
Enter fullscreen mode Exit fullscreen mode

chat.ask() sends your message and returns a TokenStream. Calling .completed() waits for the whole response and gives you back the final string, which is fine for a one-off question. But a real chat interface needs to stream tokens as they arrive, otherwise users stare at a blank screen until generation finishes.

Streaming Tokens

const response = chat.ask("What is the capital of Denmark?");

for await (const token of response) {
  console.log(token); // Each token arrives as it's generated
}
Enter fullscreen mode Exit fullscreen mode

A token is the smallest unit a model generates, typically a word, or a fragment of a word.


Multimodal Models

Some models can natively ingest images and audio. To use them, you need two things: a multimodal LLM, and its projection model that converts images and/or audio into tokens the LLM can consume (usually named with mmproj in it). A solid default that handles both image and audio is Gemma 4 with its BF16 projection model.

import { Chat } from "react-native-nobodywho";

const chat = await Chat.fromPath({
  modelPath: "/path/to/vision-model.gguf",
  projectionModelPath: "/path/to/mmproj.gguf",
});
Enter fullscreen mode Exit fullscreen mode

To actually send image or audio content, build a Prompt mixing text, images, and audio, and pass it to chat.ask() instead of a plain string:

import { Chat, Prompt } from "react-native-nobodywho";

const response = await chat
  .ask(
    new Prompt([
      Prompt.Text("Tell me what you see in the image and what you hear in the audio."),
      Prompt.Image("/path/to/dog.png"),
      Prompt.Audio("/path/to/sound.mp3"),
    ]),
  )
  .completed();
Enter fullscreen mode Exit fullscreen mode

Keep in mind that images and audio consume context fast, so you'll likely want a bigger contextSize than you'd use for text-only chat.


Speech to Text

If you'd rather transcribe spoken audio into text than have the model listen to it directly, NobodyWho integrates Whisper models in ONNX format through SpeechToText.

import { SpeechToText } from "react-native-nobodywho";

const stt = await SpeechToText.load({
  source: "hf://onnx-community/whisper-base",
});

const text = await stt.transcribeFile("recording.mp3").completed();
console.log(text);
Enter fullscreen mode Exit fullscreen mode

source is a Hugging Face repo (hf://owner/repo) or a local directory laid out the same way. Browse the Whisper ONNX models on Hugging Face to find one that fits your accuracy and speed needs.

If your audio comes from a microphone buffer rather than a file, use transcribePcm:

const text = await stt.transcribePcm(samples, 16000).completed();
Enter fullscreen mode Exit fullscreen mode

Text to Speech

Going the other direction, TextToSpeech turns text into WAV audio you can play back or save.

import { TextToSpeech } from "react-native-nobodywho";

const tts = await TextToSpeech.load({
  source: "hf://NobodyWho/Kokoro-82M",
  voice: "bf_emma",
  language: "en-gb",
});

const wav = await tts.synthesize("Hello from NobodyWho!");
// wav is a Uint8Array containing WAV bytes.
Enter fullscreen mode Exit fullscreen mode

Three architectures are supported, all ONNX-based: Kokoro, Pocket TTS, and Supertonic. NobodyWho infers which one you're using from the source string, so you only need to set architecture explicitly when loading from a custom local folder.

Each architecture has its own voice and language options that need to agree with what the model supports.


Voice Activity Detection

Before transcribing audio, it helps to know when someone is actually speaking rather than relying on a fixed silence timeout. VoiceActivityDetection uses a small model to reliably tell speech and silence apart, and pairs naturally with SpeechToText.

For streaming microphone input, push chunks in as they arrive:

import {
  VoiceActivityDetection,
  VoiceActivityDetectionEvent,
  SpeechToText,
} from "react-native-nobodywho";

const vad = await VoiceActivityDetection.load({
  sampleRate: 16000,
  source: "hf://onnx-community/silero-vad",
});
const stt = await SpeechToText.load({ source: "hf://onnx-community/whisper-base" });

while (true) {
  const chunk = readMic();
  if (vad.push(chunk) === VoiceActivityDetectionEvent.SpeechEnded) break;
}

const speech = vad.finish();
const transcription = await stt.transcribePcm(speech, 16000).completed();
console.log(transcription);
Enter fullscreen mode Exit fullscreen mode

Each push() call reports the current state (SpeechStarted, SpeechEnded, Speech, or Silence), and finish() hands you back the buffered speech segment while resetting internal state for the next turn.

If you already have a full recording and just want to pull out the speech segments from it, segment() does that in one pass:

const audio = readWavPcm("recording.wav");

for (const speech of vad.segment(audio)) {
  const transcription = await stt.transcribePcm(speech, 16000).completed();
  console.log(transcription);
}
Enter fullscreen mode Exit fullscreen mode

Sensitivity is tunable via threshold, minSpeechDurationMs, minSilenceDurationMs, and prerollDurationMs (how much audio to keep before the detected start, so you don't clip the beginning of a sentence). The defaults are a reasonable starting point, but VAD is one of those things that usually benefits from tuning to your actual environment.


Tool Calling

Tools let the model call out to real functions in your app rather than just generating text. You define a name, a description, and a set of typed parameters, and NobodyWho takes care of getting the model to call it correctly:

import { Chat, Tool } from "react-native-nobodywho";

const circleAreaTool = new Tool({
  name: "circle_area",
  description: "Calculates the area of a circle given its radius",
  parameters: [
    { name: "radius", type: "number", description: "The radius of the circle" },
  ],
  call: (radius: number) => `Area is ${(Math.PI * radius * radius).toFixed(2)}`,
});

const chat = await Chat.fromPath({
  modelPath: "huggingface:NobodyWho/Qwen_Qwen3-0.6B-GGUF/Qwen_Qwen3-0.6B-Q4_K_M.gguf",
  tools: [circleAreaTool],
});
Enter fullscreen mode Exit fullscreen mode

Not every model supports tool calling well, the Qwen family is a solid choice if you need it to be reliable. See the Tool Calling documentation for more.


RAG

Retrieval-Augmented Generation combines document search with LLM generation, so the model grounds its answers in your own knowledge base instead of what it happened to learn during training. NobodyWho provides an Encoder for embeddings and a CrossEncoder for reranking, which you can wire up as a tool the model calls when it needs to look something up:

const searchKnowledgeTool = new Tool({
  name: "search_knowledge",
  description: "Search the knowledge base for relevant information",
  parameters: [{ name: "query", type: "string", description: "The search query" }],
  call: async (query: string) => {
    const ranked = await crossencoder.rankAndSort(query, knowledge);
    return ranked.slice(0, 3).map(([doc]) => doc).join("\n");
  },
});
Enter fullscreen mode Exit fullscreen mode

See the Embeddings & RAG documentation for the full walkthrough.


What's Next?

You now have a complete foundation for building on-device AI features in React Native:

  • Download and run a GGUF model
  • Send messages and get streamed tokens back
  • Feed images and audio directly into a multimodal model
  • Transcribe speech, synthesize it back, and detect when someone's actually talking
  • Extend the model with tool calling and perform search with RAG

You can also have a look at the Expo or the React Native starter examples to see full implementation.

Links

Github - NPM - Docs

Top comments (0)