
React Native 的 AI:從雲端 API 到裝置端模型
如何為 React Native 應用程式加入 AI 功能。使用 fetch 的雲端 API 整合、使用 llama.cpp 綁定的裝置端推論,以及從前者遷移到後者的實際路徑。
React Native 讓你用一套程式碼庫同時開發 iOS 和 Android。加入 AI 功能也應該遵循相同的原則。但在 React Native 中,從「呼叫 API」到「在裝置上執行推論」的路徑與原生 Swift 或 Kotlin 不同。JavaScript 橋接、原生模組系統和跨平台模型交付都需要特定的模式。
本指南涵蓋兩種方法以及它們之間的實際遷移。
雲端 API 整合
為 React Native 應用程式加入 AI 最快的方式是呼叫雲端 API。React Native 的 fetch API 可直接與 OpenAI、Anthropic、Google Gemini 和其他供應商配合使用。
基本模式
async function generateResponse(prompt: string): Promise<string> {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
}),
});
const data = await response.json();
return data.choices[0].message.content;
}
這在 iOS 和 Android 上都能運作,不需要任何平台特定的程式碼。對於串流回應,使用 EventSource 模式或像 react-native-sse 這樣的函式庫。
聊天 UI 的串流
import EventSource from "react-native-sse";
function streamResponse(prompt: string, onToken: (token: string) => void) {
const es = new EventSource("https://api.openai.com/v1/chat/completions", {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
method: "POST",
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
stream: true,
}),
});
es.addEventListener("message", (event) => {
if (event.data === "[DONE]") return es.close();
const parsed = JSON.parse(event.data);
const token = parsed.choices[0]?.delta?.content;
if (token) onToken(token);
});
}
雲端 API 的天花板
雲端 API 對原型開發和低流量應用程式運作良好。問題與原生應用程式相同,但在 React Native 中稍微嚴重一些:
- 網路依賴: React Native 應用程式通常為跨平台覆蓋而建立,包括網路連線不穩定的市場
- 延遲: JS 橋接在 500-3,000ms 的網路往返之上額外增加約 5-10ms
- 成本擴展: 每位使用者、每次請求、每個 token 都有成本
- 隱私: 每次 API 呼叫都讓使用者資料跨越網路
React Native 中的裝置端 AI
在 React Native 中本地端執行模型意味著使用一個包裝 llama.cpp 的原生模組。JavaScript 端傳送提示並接收 token。原生端處理裝置 CPU 和 GPU 上的實際推論。
llama.rn
llama.rn 套件提供 llama.cpp 的 React Native 綁定。它暴露一個 JavaScript API,在 iOS(Metal)和 Android(CPU/Vulkan)上原生載入 GGUF 模型並執行推論。
import { initLlama } from "llama.rn";
// 載入模型
const context = await initLlama({
model: modelPath, // 裝置上 .gguf 檔案的路徑
n_ctx: 2048,
n_threads: 4,
n_gpu_layers: 32,
});
// 生成回應
const result = await context.completion({
prompt: "摘要這則筆記:...",
n_predict: 256,
temperature: 0.7,
});
console.log(result.text);
串流 Token
const result = await context.completion(
{
prompt: userPrompt,
n_predict: 512,
},
(token) => {
// 每個生成的 token 都會呼叫此函式
setResponseText((prev) => prev + token.token);
}
);
這讓你獲得與雲端 API 相同的逐 token 串流體驗,但首個 token 時間是 50-200ms,而不是 500-3,000ms。
模型交付
在 React Native 中,將 GGUF 模型檔案送到裝置上是主要的工程挑戰。
隨應用程式打包: 將模型包含在應用程式的資源中。對於 iOS,加入 Xcode 專案。對於 Android,放在 assets 目錄中或對超過 150MB 的檔案使用 Android Asset Delivery。React Native 的資源系統可以在執行時引用檔案路徑。
安裝後下載: 在首次啟動時下載模型。使用 react-native-blob-util 或 expo-file-system 進行帶有進度追蹤的背景下載:
import * as FileSystem from "expo-file-system";
const modelUri = FileSystem.documentDirectory + "model.gguf";
const download = FileSystem.createDownloadResumable(
MODEL_CDN_URL,
modelUri,
{},
(progress) => {
const pct = progress.totalBytesWritten / progress.totalBytesExpectedToWrite;
setDownloadProgress(pct);
}
);
const result = await download.downloadAsync();
效能預期
React Native 中的裝置端效能與原生應用程式幾乎相同。llama.cpp 推論在原生程式碼中執行,而不是通過 JS 橋接。橋接僅用於傳送提示和接收 token。
| 裝置 | 1B 模型 (tok/s) | 3B 模型 (tok/s) |
|---|---|---|
| iPhone 15 Pro (A17) | 35-45 | 18-25 |
| iPhone 14 (A15) | 25-35 | 12-18 |
| Galaxy S24 (SD 8 Gen 3) | 35-45 | 18-25 |
| Pixel 8 (Tensor G3) | 25-35 | 12-18 |
| 中階 Android (SD 7 Gen 3) | 18-25 | 8-12 |
JS 橋接的 token 傳遞開銷可以忽略不計(每個 token 不到 1ms)。
架構:抽象化 AI 層
最佳的 React Native 架構將 AI 提供者抽象在一個共同介面後面。這讓你可以在雲端和裝置端之間切換,而不需要更改 UI 程式碼。
interface AiProvider {
generate(prompt: string, onToken?: (token: string) => void): Promise<string>;
isReady(): boolean;
}
class CloudProvider implements AiProvider {
async generate(prompt: string, onToken?: (token: string) => void) {
// 雲端 API 呼叫
}
isReady() { return true; } // 連線時隨時可用
}
class OnDeviceProvider implements AiProvider {
async generate(prompt: string, onToken?: (token: string) => void) {
// llama.rn 推論
}
isReady() { return this.modelLoaded; }
}
這個模式支援漸進式遷移。從 CloudProvider 開始驗證。準備好時加入 OnDeviceProvider。進行 A/B 測試。最終將裝置端設為預設,雲端作為備援。
跨平台優勢
React Native 的跨平台模式對裝置端 AI 有利。你微調一個模型,匯出一個 GGUF 檔案,同時部署到 iOS 和 Android。推論函式庫處理平台差異(iOS 上的 Metal,Android 上的 CPU/Vulkan)。
與雲端 API 在每個平台上都按 token 收費相比。裝置端只需為微調和模型分發支付一次。成本不會隨平台數量倍增。
遷移路徑
- 從雲端 API 開始 使用 fetch。驗證功能、收集使用數據。
- 儘早加入抽象層(AiProvider 介面)。這不花成本,之後會有回報。
- 從 API 日誌收集訓練資料。 每次雲端 API 呼叫都是潛在的訓練範例。
- 在你的領域資料上微調小型模型。 像 Ertas 這樣的平台提供視覺化流程:上傳資料、使用 LoRA 訓練、匯出 GGUF。
- 整合 llama.rn 並在相同介面後面加入裝置端提供者。
- A/B 測試 雲端 vs 裝置端,針對真實使用者。
- 將裝置端設為預設,雲端作為不支援裝置的備援。
最終結果:一套程式碼庫、兩個平台、離線運作的 AI、零每次推論成本。
Ship AI that runs on your users' devices.
Early bird pricing starts at $14.50/mo — locked in for life. Plans for builders and agencies.
Keep reading

On-Device AI in React Native with llama.rn
How to run language models directly on the user's phone in a React Native app. Setup, model loading, streaming generation, and cross-platform considerations using llama.rn.

AI in iOS Apps: CoreML, Cloud APIs, and On-Device LLMs Compared
Three paths to AI in your iOS app. CoreML for Apple's ecosystem, cloud APIs for capability, and on-device LLMs via llama.cpp for cost and privacy. A practical comparison for Swift developers.

AI in Android Apps: ML Kit, Cloud APIs, and On-Device LLMs Compared
Three paths to AI in your Android app. Google ML Kit for common tasks, cloud APIs for full LLM capability, and on-device models via llama.cpp for cost and privacy. A practical comparison for Kotlin developers.