forked from RunanywhereAI/runanywhere-sdks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
461 lines (431 loc) · 16.2 KB
/
App.tsx
File metadata and controls
461 lines (431 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/**
* RunAnywhere AI Example App
*
* React Native demonstration app for the RunAnywhere on-device AI SDK.
*
* Architecture Pattern:
* - Two-phase SDK initialization (matching iOS pattern)
* - Module registration with models (LlamaCPP, ONNX)
* - Tab-based navigation with 5 tabs (Chat, Transcribe, Speak, Voice, Settings)
* - Tool calling settings are in Settings tab (matching iOS)
*
* Reference: iOS examples/ios/RunAnywhereAI/RunAnywhereAI/App/RunAnywhereAIApp.swift
*/
import React, { useCallback, useEffect, useState } from 'react';
import {
View,
Text,
StyleSheet,
ActivityIndicator,
TouchableOpacity,
Platform,
} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import TabNavigator from './src/navigation/TabNavigator';
import { Colors } from './src/theme/colors';
import { Typography } from './src/theme/typography';
import {
Spacing,
Padding,
BorderRadius,
IconSize,
ButtonHeight,
} from './src/theme/spacing';
// Import RunAnywhere SDK (Multi-Package Architecture)
import { RunAnywhere, SDKEnvironment, ModelCategory, initializeNitroModulesGlobally } from '@runanywhere/core';
// Make LlamaCPP optional for ONNX-only builds
let LlamaCPP: any = null;
try {
LlamaCPP = require('@runanywhere/llamacpp').LlamaCPP;
} catch (e) {
console.warn('[App] LlamaCPP backend not available - some features disabled');
}
import { ONNX, ModelArtifactType } from '@runanywhere/onnx';
import { getStoredApiKey, getStoredBaseURL, hasCustomConfiguration } from './src/screens/SettingsScreen';
/**
* App initialization state
*/
type InitState = 'loading' | 'ready' | 'error';
/**
* Initialization Loading View
*/
const InitializationLoadingView: React.FC = () => (
<View style={styles.loadingContainer}>
<View style={styles.loadingContent}>
<View style={styles.iconContainer}>
<Icon
name="hardware-chip-outline"
size={48}
color={Colors.primaryBlue}
/>
</View>
<Text style={styles.loadingTitle}>RunAnywhere AI</Text>
<Text style={styles.loadingSubtitle}>Initializing SDK...</Text>
<ActivityIndicator
size="large"
color={Colors.primaryBlue}
style={styles.spinner}
/>
</View>
</View>
);
/**
* Initialization Error View
*/
const InitializationErrorView: React.FC<{
error: string;
onRetry: () => void;
}> = ({ error, onRetry }) => (
<View style={styles.errorContainer}>
<View style={styles.errorContent}>
<View style={styles.errorIconContainer}>
<Icon name="alert-circle-outline" size={48} color={Colors.primaryRed} />
</View>
<Text style={styles.errorTitle}>Initialization Failed</Text>
<Text style={styles.errorMessage}>{error}</Text>
<TouchableOpacity style={styles.retryButton} onPress={onRetry}>
<Icon name="refresh" size={20} color={Colors.textWhite} />
<Text style={styles.retryButtonText}>Retry</Text>
</TouchableOpacity>
</View>
</View>
);
/**
* Main App Component
*/
const App: React.FC = () => {
const [initState, setInitState] = useState<InitState>('loading');
const [error, setError] = useState<string | null>(null);
/**
* Register modules and their models
* Matches iOS registerModulesAndModels() in RunAnywhereAIApp.swift
*
* Note: Model registration is async, so we need to wait for all registrations
* to complete before the UI queries models.
*/
const registerModulesAndModels = async () => {
// LlamaCPP module with LLM models (optional - skip if not built)
// Using explicit IDs ensures models are recognized after download across app restarts
const llamacppPromises = [];
if (LlamaCPP) {
LlamaCPP.register();
// Register models in parallel to avoid blocking
llamacppPromises.push(
LlamaCPP.addModel({
id: 'smollm2-360m-q8_0',
name: 'SmolLM2 360M Q8_0',
url: 'https://huggingface.co/prithivMLmods/SmolLM2-360M-GGUF/resolve/main/SmolLM2-360M.Q8_0.gguf',
memoryRequirement: 500_000_000,
}),
LlamaCPP.addModel({
id: 'llama-2-7b-chat-q4_k_m',
name: 'Llama 2 7B Chat Q4_K_M',
url: 'https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGUF/resolve/main/llama-2-7b-chat.Q4_K_M.gguf',
memoryRequirement: 4_000_000_000,
}),
LlamaCPP.addModel({
id: 'mistral-7b-instruct-q4_k_m',
name: 'Mistral 7B Instruct Q4_K_M',
url: 'https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.1-GGUF/resolve/main/mistral-7b-instruct-v0.1.Q4_K_M.gguf',
memoryRequirement: 4_000_000_000,
}),
LlamaCPP.addModel({
id: 'qwen2.5-0.5b-instruct-q6_k',
name: 'Qwen 2.5 0.5B Instruct Q6_K',
url: 'https://huggingface.co/Triangle104/Qwen2.5-0.5B-Instruct-Q6_K-GGUF/resolve/main/qwen2.5-0.5b-instruct-q6_k.gguf',
memoryRequirement: 600_000_000,
}),
// Llama 3.2 3B - Ideal for tool calling on mobile (3B params, ~1.8GB)
LlamaCPP.addModel({
id: 'llama-3.2-3b-instruct-q4_k_m',
name: 'Llama 3.2 3B Instruct Q4_K_M (Tool Calling)',
url: 'https://huggingface.co/bartowski/Llama-3.2-3B-Instruct-GGUF/resolve/main/Llama-3.2-3B-Instruct-Q4_K_M.gguf',
memoryRequirement: 2_000_000_000,
}),
LlamaCPP.addModel({
id: 'lfm2-350m-q4_k_m',
name: 'LiquidAI LFM2 350M Q4_K_M',
url: 'https://huggingface.co/LiquidAI/LFM2-350M-GGUF/resolve/main/LFM2-350M-Q4_K_M.gguf',
memoryRequirement: 250_000_000,
}),
LlamaCPP.addModel({
id: 'lfm2-350m-q8_0',
name: 'LiquidAI LFM2 350M Q8_0',
url: 'https://huggingface.co/LiquidAI/LFM2-350M-GGUF/resolve/main/LFM2-350M-Q8_0.gguf',
memoryRequirement: 400_000_000,
}),
// LFM2.5 1.2B - Best-in-class edge model from Liquid AI (1.2B params, ~700MB Q4)
// 239 tok/s on AMD CPU, designed for on-device deployment
LlamaCPP.addModel({
id: 'lfm2.5-1.2b-instruct-q4_k_m',
name: 'LiquidAI LFM2.5 1.2B Instruct Q4_K_M',
url: 'https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-GGUF/resolve/main/LFM2.5-1.2B-Instruct-Q4_K_M.gguf',
memoryRequirement: 900_000_000,
}),
// Tool Calling Optimized Models
// LFM2-1.2B-Tool - Designed for concise and precise tool calling (Liquid AI)
LlamaCPP.addModel({
id: 'lfm2-1.2b-tool-q4_k_m',
name: 'LiquidAI LFM2 1.2B Tool Q4_K_M',
url: 'https://huggingface.co/LiquidAI/LFM2-1.2B-Tool-GGUF/resolve/main/LFM2-1.2B-Tool-Q4_K_M.gguf',
memoryRequirement: 800_000_000,
}),
LlamaCPP.addModel({
id: 'lfm2-1.2b-tool-q8_0',
name: 'LiquidAI LFM2 1.2B Tool Q8_0',
url: 'https://huggingface.co/LiquidAI/LFM2-1.2B-Tool-GGUF/resolve/main/LFM2-1.2B-Tool-Q8_0.gguf',
memoryRequirement: 1_400_000_000,
})
);
// Wait for all LlamaCPP models to register
await Promise.all(llamacppPromises);
} else {
console.warn('[App] Skipping LlamaCPP models - backend not available');
}
// VLM (Vision Language) models
// VLM models require 2 files: main model + mmproj (vision projector)
// Bundled as tar.gz archives for easy download/extraction
// SmolVLM 500M - Ultra-lightweight VLM for mobile (~500MB total)
await LlamaCPP.addVLMModel({
id: 'smolvlm-500m-instruct-q8_0',
name: 'SmolVLM 500M Instruct',
url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-vlm-models-v1/smolvlm-500m-instruct-q8_0.tar.gz',
memoryRequirement: 600_000_000,
});
// ONNX module with STT and TTS models
// Using tar.gz format hosted on RunanywhereAI/sherpa-onnx for fast native extraction
// Using explicit IDs ensures models are recognized after download across app restarts
ONNX.register();
// Register ONNX models in parallel
const onnxPromises = [
ONNX.addModel({
id: 'sherpa-onnx-whisper-tiny.en',
name: 'Sherpa Whisper Tiny (ONNX)',
url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/sherpa-onnx-whisper-tiny.en.tar.gz',
modality: ModelCategory.SpeechRecognition,
artifactType: ModelArtifactType.TarGzArchive,
memoryRequirement: 75_000_000,
}),
// NOTE: whisper-small.en not included to match iOS/Android examples
// All ONNX models use tar.gz from RunanywhereAI/sherpa-onnx fork for fast native extraction
// If you need whisper-small, convert to tar.gz and upload to the fork
// TTS Models (Piper VITS)
ONNX.addModel({
id: 'vits-piper-en_US-lessac-medium',
name: 'Piper TTS (US English - Medium)',
url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/vits-piper-en_US-lessac-medium.tar.gz',
modality: ModelCategory.SpeechSynthesis,
artifactType: ModelArtifactType.TarGzArchive,
memoryRequirement: 65_000_000,
}),
ONNX.addModel({
id: 'vits-piper-en_GB-alba-medium',
name: 'Piper TTS (British English)',
url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/vits-piper-en_GB-alba-medium.tar.gz',
modality: ModelCategory.SpeechSynthesis,
artifactType: ModelArtifactType.TarGzArchive,
memoryRequirement: 65_000_000,
}),
// Embedding model for RAG
// NOTE: RAG has its own ONNXEmbeddingProvider (onnx_embedding_provider.cpp) that directly
// uses ONNX Runtime C API. It's independent from the general ONNX backend used for STT/TTS.
// The embedding model is a single ONNX file; vocab.txt is downloaded separately.
ONNX.addModel({
id: 'all-minilm-l6-v2',
name: 'All MiniLM L6 v2 (Embedding)',
url: 'https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model.onnx',
modality: ModelCategory.Embedding,
artifactType: ModelArtifactType.SingleFile,
memoryRequirement: 25_000_000,
}),
ONNX.addModel({
id: 'all-minilm-l6-v2-vocab',
name: 'All MiniLM L6 v2 (Vocab)',
url: 'https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/vocab.txt',
modality: ModelCategory.Embedding,
artifactType: ModelArtifactType.SingleFile,
memoryRequirement: 500_000,
}),
];
await Promise.all(onnxPromises);
// Diffusion (CoreML) is Swift SDK + Swift example app only. React Native does not
// depend on the Swift SDK, so we do not register diffusion models or Diffusion.register()
// on iOS here. Use the Swift example app for image generation on iOS.
console.warn('[App] All models registered');
};
/**
* Initialize the SDK
* Matches iOS initializeSDK() in RunAnywhereAIApp.swift
*/
const initializeSDK = useCallback(async () => {
setInitState('loading');
setError(null);
try {
const startTime = Date.now();
// CRITICAL: Initialize NitroModules globally FIRST to prevent JSI conflicts
console.log('[App] Initializing global NitroModules...');
await initializeNitroModulesGlobally();
console.log('[App] Global NitroModules initialized successfully');
// Check for custom API configuration (stored via Settings screen)
const customApiKey = await getStoredApiKey();
const customBaseURL = await getStoredBaseURL();
const hasCustomConfig = await hasCustomConfiguration();
if (hasCustomConfig && customApiKey && customBaseURL) {
console.log('🔧 Found custom API configuration');
console.log(` Base URL: ${customBaseURL}`);
// Custom configuration mode - use stored API key and base URL
await RunAnywhere.initialize({
apiKey: customApiKey,
baseURL: customBaseURL,
environment: SDKEnvironment.Production,
});
console.log('✅ SDK initialized with CUSTOM configuration (production)');
} else {
// DEVELOPMENT mode (default) - uses Supabase directly
// Credentials come from runanywhere-commons/development_config.cpp (git-ignored)
// This is the safest option for committing to git
await RunAnywhere.initialize({
apiKey: '', // Empty in development mode - uses C++ dev config
baseURL: 'https://api.runanywhere.ai',
environment: SDKEnvironment.Development,
});
console.log('✅ SDK initialized in DEVELOPMENT mode (Supabase via C++ config)');
}
// Register modules and models (await to ensure models are ready before UI)
await registerModulesAndModels();
const initTime = Date.now() - startTime;
// Get SDK info for debugging
const isInit = await RunAnywhere.isInitialized();
const version = await RunAnywhere.getVersion();
const backendInfo = await RunAnywhere.getBackendInfo();
// Log initialization summary
// eslint-disable-next-line no-console
console.log(
`[App] SDK initialized: v${version}, ${isInit ? 'Active' : 'Inactive'}, ${initTime}ms, env: ${JSON.stringify(backendInfo)}`
);
setInitState('ready');
} catch (err) {
console.error('[App] SDK initialization failed:', err);
const errorMessage =
err instanceof Error ? err.message : 'Unknown error occurred';
setError(errorMessage);
setInitState('error');
}
}, []);
useEffect(() => {
// Defer initialization to avoid blocking React's initial render and causing ANR
// Schedule on next event loop iteration to ensure React can render the loading screen first
const timeoutId = setTimeout(() => {
initializeSDK();
}, 100);
return () => clearTimeout(timeoutId);
}, [initializeSDK]);
// Render based on state
if (initState === 'loading') {
return (
<SafeAreaProvider>
<InitializationLoadingView />
</SafeAreaProvider>
);
}
if (initState === 'error') {
return (
<SafeAreaProvider>
<InitializationErrorView
error={error || 'Failed to initialize SDK'}
onRetry={initializeSDK}
/>
</SafeAreaProvider>
);
}
return (
<SafeAreaProvider>
<NavigationContainer>
<TabNavigator />
</NavigationContainer>
</SafeAreaProvider>
);
};
const styles = StyleSheet.create({
// Loading View
loadingContainer: {
flex: 1,
backgroundColor: Colors.backgroundPrimary,
justifyContent: 'center',
alignItems: 'center',
},
loadingContent: {
alignItems: 'center',
},
iconContainer: {
width: IconSize.huge,
height: IconSize.huge,
borderRadius: IconSize.huge / 2,
backgroundColor: Colors.badgeBlue,
justifyContent: 'center',
alignItems: 'center',
marginBottom: Spacing.xLarge,
},
loadingTitle: {
...Typography.title,
color: Colors.textPrimary,
marginBottom: Spacing.small,
},
loadingSubtitle: {
...Typography.body,
color: Colors.textSecondary,
marginBottom: Spacing.xLarge,
},
spinner: {
marginTop: Spacing.large,
},
// Error View
errorContainer: {
flex: 1,
backgroundColor: Colors.backgroundPrimary,
justifyContent: 'center',
alignItems: 'center',
padding: Padding.padding24,
},
errorContent: {
alignItems: 'center',
maxWidth: 300,
},
errorIconContainer: {
width: IconSize.huge,
height: IconSize.huge,
borderRadius: IconSize.huge / 2,
backgroundColor: Colors.badgeRed,
justifyContent: 'center',
alignItems: 'center',
marginBottom: Spacing.xLarge,
},
errorTitle: {
...Typography.title2,
color: Colors.textPrimary,
marginBottom: Spacing.medium,
},
errorMessage: {
...Typography.body,
color: Colors.textSecondary,
textAlign: 'center',
marginBottom: Spacing.xLarge,
},
retryButton: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: Spacing.smallMedium,
backgroundColor: Colors.primaryBlue,
paddingHorizontal: Padding.padding24,
height: ButtonHeight.regular,
borderRadius: BorderRadius.large,
},
retryButtonText: {
...Typography.headline,
color: Colors.textWhite,
},
});
export default App;