React Nativellama.cppon-device AIcross-platformllama.rn
在 React Native 中使用 llama.rn 實現裝置端 AI
如何在 React Native 應用程式中直接在使用者手機上運行語言模型。使用 llama.rn 的設定、模型載入、串流生成和跨平台考量。
Edward Xi Yang
llama.rn 是一個 React Native 函式庫,提供連接 llama.cpp 的 JavaScript 繫結。它透過相同的 JavaScript API 在 iOS(Metal)和 Android(CPU/Vulkan)上原生運行 GGUF 語言模型。
對 React Native 開發者來說,這意味著一套程式碼、一個 API、零雲端依賴的裝置端 AI。
安裝
npm install llama.rn
# 或
yarn add llama.rniOS 需執行 pod install:
cd ios && pod installAndroid 上,原生函式庫會透過 autolinking 自動包含。
Expo
如果您使用 Expo,由於 llama.rn 包含原生程式碼,需要開發建置版本(非 Expo Go):
npx expo prebuild
npx expo run:ios # 或 run:android載入模型
import { initLlama, LlamaContext } from "llama.rn";
let context: LlamaContext | null = null;
async function loadModel(modelPath: string) {
context = await initLlama({
model: modelPath,
n_ctx: 2048, // 上下文視窗
n_threads: 4, // CPU 執行緒
n_gpu_layers: 99, // 卸載到 GPU(Metal/Vulkan)
use_mlock: true, // 鎖定模型在記憶體中
});
console.log("Model loaded successfully");
}模型路徑
模型路徑必須指向裝置檔案系統上的本地文件。如何將文件放到裝置上取決於您的交付策略: