@runanywhere/llamacpp 0.18.0 → 0.19.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +85 -413
  2. package/RunAnywhereLlama.podspec +27 -13
  3. package/android/CMakeLists.txt +37 -20
  4. package/android/build.gradle +83 -8
  5. package/cpp/HybridRunAnywhereLlama.cpp +26 -269
  6. package/cpp/HybridRunAnywhereLlama.hpp +2 -58
  7. package/ios/{Frameworks → Binaries}/RABackendLLAMACPP.xcframework/Info.plist +8 -9
  8. package/ios/{Frameworks/RABackendLLAMACPP.xcframework/ios-arm64/RABackendLLAMACPP.framework/RABackendLLAMACPP → Binaries/RABackendLLAMACPP.xcframework/ios-arm64/librac_backend_llamacpp.a} +0 -0
  9. package/ios/{Frameworks/RABackendLLAMACPP.xcframework/ios-arm64_x86_64-simulator/RABackendLLAMACPP.framework/RABackendLLAMACPP → Binaries/RABackendLLAMACPP.xcframework/ios-arm64-simulator/librac_backend_llamacpp.a} +0 -0
  10. package/nitrogen/generated/android/kotlin/com/margelo/nitro/runanywhere/llama/runanywherellamaOnLoad.kt +1 -1
  11. package/nitrogen/generated/android/runanywherellama+autolinking.cmake +2 -2
  12. package/nitrogen/generated/android/runanywherellama+autolinking.gradle +1 -1
  13. package/nitrogen/generated/android/runanywherellamaOnLoad.cpp +23 -18
  14. package/nitrogen/generated/android/runanywherellamaOnLoad.hpp +14 -5
  15. package/nitrogen/generated/ios/RunAnywhereLlama+autolinking.rb +4 -2
  16. package/nitrogen/generated/ios/RunAnywhereLlama-Swift-Cxx-Bridge.cpp +2 -2
  17. package/nitrogen/generated/ios/RunAnywhereLlama-Swift-Cxx-Bridge.hpp +2 -2
  18. package/nitrogen/generated/ios/RunAnywhereLlama-Swift-Cxx-Umbrella.hpp +1 -1
  19. package/nitrogen/generated/ios/RunAnywhereLlamaAutolinking.mm +1 -1
  20. package/nitrogen/generated/ios/RunAnywhereLlamaAutolinking.swift +6 -2
  21. package/nitrogen/generated/shared/c++/HybridRunAnywhereLlamaSpec.cpp +1 -11
  22. package/nitrogen/generated/shared/c++/HybridRunAnywhereLlamaSpec.hpp +2 -15
  23. package/package.json +13 -10
  24. package/react-native.config.js +1 -3
  25. package/src/LlamaCPP.ts +32 -160
  26. package/src/LlamaCppProvider.ts +32 -36
  27. package/src/index.ts +18 -23
  28. package/src/native/NativeRunAnywhereLlama.ts +19 -5
  29. package/src/specs/RunAnywhereLlama.nitro.ts +17 -126
  30. package/android/src/main/AndroidManifest.xml +0 -3
  31. package/android/src/main/cpp/cpp-adapter.cpp +0 -14
  32. package/android/src/main/include/rac/backends/rac_llm_llamacpp.h +0 -218
  33. package/android/src/main/include/rac/backends/rac_stt_onnx.h +0 -99
  34. package/android/src/main/include/rac/backends/rac_stt_whispercpp.h +0 -153
  35. package/android/src/main/include/rac/backends/rac_tts_onnx.h +0 -71
  36. package/android/src/main/include/rac/backends/rac_vad_onnx.h +0 -84
  37. package/android/src/main/include/rac/core/capabilities/rac_lifecycle.h +0 -290
  38. package/android/src/main/include/rac/core/rac_analytics_events.h +0 -610
  39. package/android/src/main/include/rac/core/rac_audio_utils.h +0 -88
  40. package/android/src/main/include/rac/core/rac_component_types.h +0 -160
  41. package/android/src/main/include/rac/core/rac_core.h +0 -331
  42. package/android/src/main/include/rac/core/rac_error.h +0 -469
  43. package/android/src/main/include/rac/core/rac_events.h +0 -334
  44. package/android/src/main/include/rac/core/rac_logger.h +0 -416
  45. package/android/src/main/include/rac/core/rac_platform_adapter.h +0 -340
  46. package/android/src/main/include/rac/core/rac_sdk_state.h +0 -292
  47. package/android/src/main/include/rac/core/rac_structured_error.h +0 -594
  48. package/android/src/main/include/rac/core/rac_types.h +0 -264
  49. package/android/src/main/include/rac/features/llm/rac_llm.h +0 -17
  50. package/android/src/main/include/rac/features/llm/rac_llm_analytics.h +0 -188
  51. package/android/src/main/include/rac/features/llm/rac_llm_component.h +0 -228
  52. package/android/src/main/include/rac/features/llm/rac_llm_events.h +0 -215
  53. package/android/src/main/include/rac/features/llm/rac_llm_metrics.h +0 -402
  54. package/android/src/main/include/rac/features/llm/rac_llm_service.h +0 -163
  55. package/android/src/main/include/rac/features/llm/rac_llm_structured_output.h +0 -141
  56. package/android/src/main/include/rac/features/llm/rac_llm_types.h +0 -384
  57. package/android/src/main/include/rac/features/platform/rac_llm_platform.h +0 -204
  58. package/android/src/main/include/rac/features/platform/rac_tts_platform.h +0 -197
  59. package/android/src/main/include/rac/features/stt/rac_stt.h +0 -17
  60. package/android/src/main/include/rac/features/stt/rac_stt_analytics.h +0 -204
  61. package/android/src/main/include/rac/features/stt/rac_stt_component.h +0 -162
  62. package/android/src/main/include/rac/features/stt/rac_stt_events.h +0 -62
  63. package/android/src/main/include/rac/features/stt/rac_stt_service.h +0 -154
  64. package/android/src/main/include/rac/features/stt/rac_stt_types.h +0 -389
  65. package/android/src/main/include/rac/features/tts/rac_tts.h +0 -17
  66. package/android/src/main/include/rac/features/tts/rac_tts_analytics.h +0 -181
  67. package/android/src/main/include/rac/features/tts/rac_tts_component.h +0 -158
  68. package/android/src/main/include/rac/features/tts/rac_tts_events.h +0 -54
  69. package/android/src/main/include/rac/features/tts/rac_tts_service.h +0 -162
  70. package/android/src/main/include/rac/features/tts/rac_tts_types.h +0 -374
  71. package/android/src/main/include/rac/features/vad/rac_vad.h +0 -17
  72. package/android/src/main/include/rac/features/vad/rac_vad_analytics.h +0 -236
  73. package/android/src/main/include/rac/features/vad/rac_vad_component.h +0 -185
  74. package/android/src/main/include/rac/features/vad/rac_vad_energy.h +0 -443
  75. package/android/src/main/include/rac/features/vad/rac_vad_events.h +0 -76
  76. package/android/src/main/include/rac/features/vad/rac_vad_service.h +0 -167
  77. package/android/src/main/include/rac/features/vad/rac_vad_types.h +0 -244
  78. package/android/src/main/include/rac/features/voice_agent/rac_voice_agent.h +0 -612
  79. package/android/src/main/include/rac/infrastructure/device/rac_device_manager.h +0 -176
  80. package/android/src/main/include/rac/infrastructure/download/rac_download.h +0 -418
  81. package/android/src/main/include/rac/infrastructure/events/rac_events.h +0 -177
  82. package/android/src/main/include/rac/infrastructure/model_management/rac_model_assignment.h +0 -169
  83. package/android/src/main/include/rac/infrastructure/model_management/rac_model_paths.h +0 -258
  84. package/android/src/main/include/rac/infrastructure/model_management/rac_model_registry.h +0 -357
  85. package/android/src/main/include/rac/infrastructure/model_management/rac_model_strategy.h +0 -374
  86. package/android/src/main/include/rac/infrastructure/model_management/rac_model_types.h +0 -613
  87. package/android/src/main/include/rac/infrastructure/network/rac_api_types.h +0 -335
  88. package/android/src/main/include/rac/infrastructure/network/rac_auth_manager.h +0 -252
  89. package/android/src/main/include/rac/infrastructure/network/rac_dev_config.h +0 -85
  90. package/android/src/main/include/rac/infrastructure/network/rac_endpoints.h +0 -102
  91. package/android/src/main/include/rac/infrastructure/network/rac_environment.h +0 -220
  92. package/android/src/main/include/rac/infrastructure/network/rac_http_client.h +0 -233
  93. package/android/src/main/include/rac/infrastructure/storage/rac_storage_analyzer.h +0 -286
  94. package/android/src/main/include/rac/infrastructure/telemetry/rac_telemetry_manager.h +0 -206
  95. package/android/src/main/include/rac/infrastructure/telemetry/rac_telemetry_types.h +0 -234
  96. package/android/src/main/java/com/margelo/nitro/runanywhere/llama/RunAnywhereLlamaPackage.kt +0 -35
  97. package/android/src/main/jniLibs/arm64-v8a/libomp.so +0 -0
  98. package/android/src/main/jniLibs/arm64-v8a/librac_backend_llamacpp.so +0 -0
  99. package/android/src/main/jniLibs/arm64-v8a/librac_backend_llamacpp_jni.so +0 -0
  100. package/android/src/main/jniLibs/arm64-v8a/librac_commons.so +0 -0
  101. package/android/src/main/jniLibs/x86_64/libomp.so +0 -0
  102. package/android/src/main/jniLibs/x86_64/librac_backend_llamacpp.so +0 -0
  103. package/android/src/main/jniLibs/x86_64/librac_backend_llamacpp_jni.so +0 -0
  104. package/android/src/main/jniLibs/x86_64/librac_commons.so +0 -0
  105. package/cpp/bridges/LLMBridge.cpp +0 -209
  106. package/cpp/bridges/LLMBridge.hpp +0 -109
  107. package/cpp/bridges/StructuredOutputBridge.cpp +0 -151
  108. package/cpp/bridges/StructuredOutputBridge.hpp +0 -66
  109. package/cpp/rac_llm_llamacpp.h +0 -34
  110. package/ios/Frameworks/RABackendLLAMACPP.xcframework/ios-arm64/RABackendLLAMACPP.framework/Headers/RABackendLLAMACPP.h +0 -2
  111. package/ios/Frameworks/RABackendLLAMACPP.xcframework/ios-arm64/RABackendLLAMACPP.framework/Info.plist +0 -11
  112. package/ios/Frameworks/RABackendLLAMACPP.xcframework/ios-arm64/RABackendLLAMACPP.framework/Modules/module.modulemap +0 -5
  113. package/ios/Frameworks/RABackendLLAMACPP.xcframework/ios-arm64_x86_64-simulator/RABackendLLAMACPP.framework/Headers/RABackendLLAMACPP.h +0 -2
  114. package/ios/Frameworks/RABackendLLAMACPP.xcframework/ios-arm64_x86_64-simulator/RABackendLLAMACPP.framework/Info.plist +0 -11
  115. package/ios/Frameworks/RABackendLLAMACPP.xcframework/ios-arm64_x86_64-simulator/RABackendLLAMACPP.framework/Modules/module.modulemap +0 -5
  116. package/ios/LlamaCPPBackend.podspec +0 -127
package/src/LlamaCPP.ts CHANGED
@@ -2,205 +2,77 @@
2
2
  * @runanywhere/llamacpp - LlamaCPP Module
3
3
  *
4
4
  * LlamaCPP module wrapper for RunAnywhere React Native SDK.
5
- * Provides public API for module registration and model declaration.
5
+ * Provides public API for module registration only.
6
6
  *
7
- * This mirrors the Swift SDK's LlamaCPP module pattern:
8
- * - LlamaCPP.register() - Register the module with ServiceRegistry
9
- * - LlamaCPP.addModel() - Declare a model for this module
7
+ * Model registration is done via RunAnywhere.registerModel() / RunAnywhere.registerMultiFileModel()
8
+ * on the core SDK, matching the Swift SDK pattern where LlamaCPP only exposes
9
+ * register() and unregister().
10
10
  *
11
- * Reference: sdk/runanywhere-swift/Sources/LlamaCPPRuntime/LlamaCPPServiceProvider.swift
11
+ * Reference: sdk/runanywhere-swift/Sources/LlamaCPPRuntime/LlamaCPP.swift
12
12
  */
13
13
 
14
14
  import { LlamaCppProvider } from './LlamaCppProvider';
15
- import {
16
- ModelRegistry,
17
- FileSystem,
18
- LLMFramework,
19
- ModelCategory,
20
- ModelFormat,
21
- ConfigurationSource,
22
- SDKLogger,
23
- type ModelInfo,
24
- } from '@runanywhere/core';
15
+ import { SDKLogger } from '@runanywhere/core/internal';
25
16
 
26
- // SDKLogger instance for this module
27
17
  const log = new SDKLogger('LLM.LlamaCpp');
28
18
 
29
- /**
30
- * Model registration options for LlamaCPP models
31
- *
32
- * Matches iOS: LlamaCPP.addModel() parameter structure
33
- */
34
- export interface LlamaCPPModelOptions {
35
- /** Unique model ID. If not provided, generated from URL filename */
36
- id?: string;
37
- /** Display name for the model */
38
- name: string;
39
- /** Download URL for the model */
40
- url: string;
41
- /** Model category (defaults to Language for LLM models) */
42
- modality?: ModelCategory;
43
- /** Memory requirement in bytes */
44
- memoryRequirement?: number;
45
- /** Whether model supports reasoning/thinking tokens */
46
- supportsThinking?: boolean;
47
- }
48
-
49
19
  /**
50
20
  * LlamaCPP Module
51
21
  *
52
- * Public API for registering LlamaCPP module and declaring GGUF models.
53
- * This provides the same developer experience as the iOS SDK.
22
+ * Matches iOS: public enum LlamaCPP: RunAnywhereModule
23
+ *
24
+ * Only provides backend registration. Model registration is done via
25
+ * RunAnywhere.registerModel() on the core SDK.
54
26
  *
55
27
  * ## Usage
56
28
  *
57
29
  * ```typescript
58
30
  * import { LlamaCPP } from '@runanywhere/llamacpp';
31
+ * import { RunAnywhere } from '@runanywhere/core';
32
+ * // Register LlamaCPP backend
33
+ * await LlamaCPP.register();
59
34
  *
60
- * // Register module
61
- * LlamaCPP.register();
62
- *
63
- * // Add models
64
- * LlamaCPP.addModel({
35
+ * // Register models via RunAnywhere (matching iOS pattern)
36
+ * await RunAnywhere.registerModel({
65
37
  * id: 'smollm2-360m-q8_0',
66
38
  * name: 'SmolLM2 360M Q8_0',
67
- * url: 'https://huggingface.co/prithivMLmods/SmolLM2-360M-GGUF/resolve/main/SmolLM2-360M.Q8_0.gguf',
39
+ * url: '...',
40
+ * framework: InferenceFramework.INFERENCE_FRAMEWORK_LLAMA_CPP,
68
41
  * memoryRequirement: 500_000_000
69
42
  * });
70
43
  * ```
71
- *
72
- * Matches iOS: public enum LlamaCPP: RunAnywhereModule
73
44
  */
74
45
  export const LlamaCPP = {
75
- /**
76
- * Module metadata
77
- * Matches iOS: static let moduleId, moduleName, inferenceFramework
78
- */
79
- moduleId: 'llamacpp',
80
- moduleName: 'LlamaCPP',
81
- inferenceFramework: LLMFramework.LlamaCpp,
82
- capabilities: ['llm'] as const,
83
- defaultPriority: 100,
84
-
85
46
  /**
86
47
  * Register LlamaCPP module with the SDK
87
48
  *
88
- * This registers the LlamaCPP provider with ServiceRegistry,
89
- * enabling it to handle GGUF models.
49
+ * Registers the LlamaCPP LLM and VLM providers with ServiceRegistry.
90
50
  *
91
51
  * Matches iOS: static func register(priority: Int = defaultPriority)
92
- *
93
- * @example
94
- * ```typescript
95
- * LlamaCPP.register();
96
- * ```
97
52
  */
98
- register(): void {
53
+ async register(): Promise<boolean> {
99
54
  log.debug('Registering LlamaCPP module');
100
- LlamaCppProvider.register();
101
- log.info('LlamaCPP module registered');
55
+ const registered = await LlamaCppProvider.register();
56
+ if (registered) {
57
+ log.info('LlamaCPP module registered');
58
+ }
59
+ return registered;
102
60
  },
103
61
 
104
62
  /**
105
- * Add a model to this module
63
+ * Unregister LlamaCPP module from the SDK
106
64
  *
107
- * Registers a GGUF model with the ModelRegistry.
108
- * The model will use LlamaCPP framework automatically.
109
- *
110
- * Matches iOS: static func addModel(id:name:url:modality:memoryRequirement:supportsThinking:)
111
- *
112
- * @param options - Model registration options
113
- * @returns Promise resolving to the created ModelInfo
114
- *
115
- * @example
116
- * ```typescript
117
- * await LlamaCPP.addModel({
118
- * id: 'llama-2-7b-chat-q4_k_m',
119
- * name: 'Llama 2 7B Chat Q4_K_M',
120
- * url: 'https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGUF/resolve/main/llama-2-7b-chat.Q4_K_M.gguf',
121
- * memoryRequirement: 4_000_000_000
122
- * });
123
- * ```
65
+ * Matches iOS: static func unregister()
124
66
  */
125
- async addModel(options: LlamaCPPModelOptions): Promise<ModelInfo> {
126
- // Generate stable ID from URL if not provided
127
- const modelId = options.id ?? this._generateModelId(options.url);
128
-
129
- // Determine modality (default to Language for LLM)
130
- const category = options.modality ?? ModelCategory.Language;
131
-
132
- // Infer format from URL
133
- const format = options.url.toLowerCase().includes('.gguf')
134
- ? ModelFormat.GGUF
135
- : ModelFormat.GGML;
136
-
137
- const now = new Date().toISOString();
138
-
139
- // Check if model already exists on disk (persistence across sessions)
140
- let isDownloaded = false;
141
- let localPath: string | undefined;
142
-
143
- if (FileSystem.isAvailable()) {
144
- try {
145
- const exists = await FileSystem.modelExists(modelId, 'LlamaCpp');
146
- if (exists) {
147
- localPath = await FileSystem.getModelPath(modelId, 'LlamaCpp');
148
- isDownloaded = true;
149
- log.debug(`Model ${modelId} found on disk: ${localPath}`);
150
- }
151
- } catch (error) {
152
- // Ignore errors checking for existing model
153
- log.debug(`Could not check for existing model ${modelId}: ${error}`);
154
- }
155
- }
156
-
157
- const modelInfo: ModelInfo = {
158
- id: modelId,
159
- name: options.name,
160
- category,
161
- format,
162
- downloadURL: options.url,
163
- localPath,
164
- downloadSize: undefined,
165
- memoryRequired: options.memoryRequirement,
166
- compatibleFrameworks: [LLMFramework.LlamaCpp],
167
- preferredFramework: LLMFramework.LlamaCpp,
168
- supportsThinking: options.supportsThinking ?? false,
169
- metadata: { tags: [] },
170
- source: ConfigurationSource.Local,
171
- createdAt: now,
172
- updatedAt: now,
173
- syncPending: false,
174
- usageCount: 0,
175
- isDownloaded,
176
- isAvailable: true,
177
- };
178
-
179
- // Register with ModelRegistry and wait for completion
180
- await ModelRegistry.registerModel(modelInfo);
181
-
182
- log.info(`Added model: ${modelId} (${options.name})`, {
183
- modelId,
184
- isDownloaded,
185
- });
186
-
187
- return modelInfo;
67
+ async unregister(): Promise<boolean> {
68
+ log.info('Unregistering LlamaCPP module');
69
+ return LlamaCppProvider.unregister();
188
70
  },
189
71
 
190
72
  /**
191
- * Generate a stable model ID from URL
192
- * @internal
73
+ * Check if this module is registered with the native backend registry.
193
74
  */
194
- _generateModelId(url: string): string {
195
- try {
196
- const urlObj = new URL(url);
197
- const pathname = urlObj.pathname;
198
- const filename = pathname.split('/').pop() ?? 'model';
199
- // Remove common extensions
200
- return filename.replace(/\.(gguf|ggml|bin)$/i, '');
201
- } catch {
202
- // Fallback for invalid URLs
203
- return `model-${Date.now()}`;
204
- }
75
+ async isRegistered(): Promise<boolean> {
76
+ return LlamaCppProvider.isRegistered();
205
77
  },
206
78
  };
@@ -1,49 +1,44 @@
1
1
  /**
2
2
  * @runanywhere/llamacpp - LlamaCPP Provider
3
3
  *
4
- * LlamaCPP module registration for React Native SDK.
5
- * Thin wrapper that triggers C++ backend registration.
4
+ * Internal LlamaCPP module registration for React Native SDK.
5
+ * Thin wrapper that triggers C++ backend registration behind the LlamaCPP facade.
6
6
  *
7
7
  * Reference: sdk/runanywhere-swift/Sources/LlamaCPPRuntime/LlamaCPP.swift
8
8
  */
9
9
 
10
10
  import { requireNativeLlamaModule, isNativeLlamaModuleAvailable } from './native/NativeRunAnywhereLlama';
11
- import { SDKLogger } from '@runanywhere/core';
11
+ import { SDKLogger } from '@runanywhere/core/internal';
12
12
 
13
13
  // SDKLogger instance for this module
14
14
  const log = new SDKLogger('LLM.LlamaCppProvider');
15
15
 
16
16
  /**
17
- * LlamaCPP Module
17
+ * Internal LlamaCPP provider implementation.
18
18
  *
19
- * Provides LLM capabilities using llama.cpp with GGUF models.
20
- * The actual service is provided by the C++ backend.
19
+ * Registers the llama.cpp backend provider; the single C++ registration call
20
+ * covers both LLM and VLM modalities. Core owns public model lifecycle and
21
+ * inference surfaces.
21
22
  *
22
- * ## Registration
23
- *
24
- * ```typescript
25
- * import { LlamaCppProvider } from '@runanywhere/llamacpp';
26
- *
27
- * // Register the backend
28
- * await LlamaCppProvider.register();
29
- * ```
23
+ * @internal
30
24
  */
31
25
  export class LlamaCppProvider {
32
26
  static readonly moduleId = 'llamacpp';
33
27
  static readonly moduleName = 'LlamaCPP';
34
28
  static readonly version = '2.0.0';
35
29
 
36
- private static isRegistered = false;
30
+ private static registered = false;
37
31
 
38
32
  /**
39
33
  * Register LlamaCPP backend with the C++ service registry.
40
34
  * Calls rac_backend_llamacpp_register() to register the
41
- * LlamaCPP service provider with the C++ commons layer.
35
+ * LlamaCPP service provider with the C++ commons layer; the single call
36
+ * covers both LLM and VLM modalities.
42
37
  * Safe to call multiple times - subsequent calls are no-ops.
43
38
  * @returns Promise<boolean> true if registered successfully
44
39
  */
45
40
  static async register(): Promise<boolean> {
46
- if (this.isRegistered) {
41
+ if (this.registered) {
47
42
  log.debug('LlamaCPP already registered, returning');
48
43
  return true;
49
44
  }
@@ -60,8 +55,8 @@ export class LlamaCppProvider {
60
55
  // Call the native registration method from the Llama module
61
56
  const success = await native.registerBackend();
62
57
  if (success) {
63
- this.isRegistered = true;
64
- log.info('LlamaCPP backend registered successfully');
58
+ this.registered = true;
59
+ log.info('LlamaCPP backend registered successfully (covers LLM and VLM)');
65
60
  }
66
61
  return success;
67
62
  } catch (error) {
@@ -73,10 +68,11 @@ export class LlamaCppProvider {
73
68
 
74
69
  /**
75
70
  * Unregister the LlamaCPP backend from C++ registry.
71
+ * The single unregistration call covers both LLM and VLM modalities.
76
72
  * @returns Promise<boolean> true if unregistered successfully
77
73
  */
78
74
  static async unregister(): Promise<boolean> {
79
- if (!this.isRegistered) {
75
+ if (!this.registered) {
80
76
  return true;
81
77
  }
82
78
 
@@ -84,11 +80,12 @@ export class LlamaCppProvider {
84
80
  return false;
85
81
  }
86
82
 
83
+ const native = requireNativeLlamaModule();
84
+
87
85
  try {
88
- const native = requireNativeLlamaModule();
89
86
  const success = await native.unregisterBackend();
90
87
  if (success) {
91
- this.isRegistered = false;
88
+ this.registered = false;
92
89
  log.debug('LlamaCPP backend unregistered');
93
90
  }
94
91
  return success;
@@ -99,22 +96,21 @@ export class LlamaCppProvider {
99
96
  }
100
97
 
101
98
  /**
102
- * Check if LlamaCPP can handle a given model
99
+ * Check native registration state. Falls back to JS state if the native
100
+ * object cannot be created.
103
101
  */
104
- static canHandle(modelId: string | null | undefined): boolean {
105
- if (!modelId) {
102
+ static async isRegistered(): Promise<boolean> {
103
+ if (!isNativeLlamaModuleAvailable()) {
106
104
  return false;
107
105
  }
108
- const lowercased = modelId.toLowerCase();
109
- return lowercased.includes('gguf') || lowercased.endsWith('.gguf');
110
- }
111
- }
112
106
 
113
- /**
114
- * Auto-register when module is imported
115
- */
116
- export function autoRegister(): void {
117
- LlamaCppProvider.register().catch(() => {
118
- // Silently handle registration failure during auto-registration
119
- });
107
+ try {
108
+ const native = requireNativeLlamaModule();
109
+ const registered = await native.isBackendRegistered();
110
+ this.registered = registered;
111
+ return registered;
112
+ } catch {
113
+ return this.registered;
114
+ }
115
+ }
120
116
  }
package/src/index.ts CHANGED
@@ -1,32 +1,40 @@
1
1
  /**
2
2
  * @runanywhere/llamacpp - LlamaCPP Backend for RunAnywhere React Native SDK
3
3
  *
4
- * This package provides the LlamaCPP backend for on-device LLM inference.
5
- * It supports GGUF models and provides the same API as the iOS SDK.
4
+ * This package registers the LlamaCPP native providers. Public model
5
+ * lifecycle, generation, VLM, structured-output, and LoRA APIs live in
6
+ * @runanywhere/core.
6
7
  *
7
8
  * ## Usage
8
9
  *
9
10
  * ```typescript
10
11
  * import { RunAnywhere } from '@runanywhere/core';
11
- * import { LlamaCPP, LlamaCppProvider } from '@runanywhere/llamacpp';
12
+ * import { InferenceFramework, ModelCategory } from '@runanywhere/proto-ts/model_types';
13
+ * import { ModelLoadRequest } from '@runanywhere/proto-ts/model_types';
14
+ * import { LlamaCPP } from '@runanywhere/llamacpp';
12
15
  *
13
16
  * // Initialize core SDK
14
17
  * await RunAnywhere.initialize({ apiKey: 'your-key' });
15
18
  *
16
- * // Register LlamaCPP backend (calls native rac_backend_llamacpp_register)
17
- * await LlamaCppProvider.register();
19
+ * // Register LlamaCPP backend providers
20
+ * await LlamaCPP.register();
18
21
  *
19
- * // Add a model
20
- * LlamaCPP.addModel({
22
+ * // Register models via RunAnywhere (matching iOS pattern)
23
+ * await RunAnywhere.registerModel({
21
24
  * id: 'smollm2-360m-q8_0',
22
25
  * name: 'SmolLM2 360M Q8_0',
23
26
  * url: 'https://huggingface.co/.../SmolLM2-360M.Q8_0.gguf',
27
+ * framework: InferenceFramework.INFERENCE_FRAMEWORK_LLAMA_CPP,
24
28
  * memoryRequirement: 500_000_000
25
29
  * });
26
30
  *
27
31
  * // Download and use
28
- * await RunAnywhere.downloadModel('smollm2-360m-q8_0');
29
- * await RunAnywhere.loadModel('smollm2-360m-q8_0');
32
+ * const download = RunAnywhere.downloadModel('smollm2-360m-q8_0')[Symbol.asyncIterator]();
33
+ * while (!(await download.next()).done) {}
34
+ * await RunAnywhere.loadModel(ModelLoadRequest.fromPartial({
35
+ * modelId: 'smollm2-360m-q8_0',
36
+ * category: ModelCategory.MODEL_CATEGORY_LANGUAGE,
37
+ * }));
30
38
  * const result = await RunAnywhere.generate('Hello, world!');
31
39
  * ```
32
40
  *
@@ -37,20 +45,7 @@
37
45
  // Main API
38
46
  // =============================================================================
39
47
 
40
- export { LlamaCPP, type LlamaCPPModelOptions } from './LlamaCPP';
41
- export { LlamaCppProvider, autoRegister } from './LlamaCppProvider';
42
-
43
- // =============================================================================
44
- // Native Module
45
- // =============================================================================
46
-
47
- export {
48
- NativeRunAnywhereLlama,
49
- getNativeLlamaModule,
50
- requireNativeLlamaModule,
51
- isNativeLlamaModuleAvailable,
52
- } from './native/NativeRunAnywhereLlama';
53
- export type { NativeRunAnywhereLlamaModule } from './native/NativeRunAnywhereLlama';
48
+ export { LlamaCPP } from './LlamaCPP';
54
49
 
55
50
  // =============================================================================
56
51
  // Nitrogen Spec Types
@@ -2,11 +2,16 @@
2
2
  * NativeRunAnywhereLlama.ts
3
3
  *
4
4
  * Exports the native RunAnywhereLlama Hybrid Object from Nitro Modules.
5
- * This module provides Llama-based text generation capabilities.
5
+ * This module provides LlamaCPP backend registration hooks.
6
6
  */
7
7
 
8
- import { NitroModules } from 'react-native-nitro-modules';
9
8
  import type { RunAnywhereLlama } from '../specs/RunAnywhereLlama.nitro';
9
+ import { getNitroModulesProxySync, type NitroProxy } from '@runanywhere/core/internal';
10
+
11
+ // Use the global NitroModules initialization
12
+ function getNitroModulesProxy(): NitroProxy | null {
13
+ return getNitroModulesProxySync();
14
+ }
10
15
 
11
16
  /**
12
17
  * The native RunAnywhereLlama module type
@@ -17,15 +22,24 @@ export type NativeRunAnywhereLlamaModule = RunAnywhereLlama;
17
22
  * Get the native RunAnywhereLlama Hybrid Object
18
23
  */
19
24
  export function requireNativeLlamaModule(): NativeRunAnywhereLlamaModule {
20
- return NitroModules.createHybridObject<RunAnywhereLlama>('RunAnywhereLlama');
25
+ const NitroProxy = getNitroModulesProxy();
26
+ if (!NitroProxy) {
27
+ throw new Error(
28
+ 'NitroModules is not available. This can happen in Bridgeless mode if ' +
29
+ 'react-native-nitro-modules is not properly linked.'
30
+ );
31
+ }
32
+ return NitroProxy.createHybridObject('RunAnywhereLlama') as RunAnywhereLlama;
21
33
  }
22
34
 
23
35
  /**
24
- * Check if the native Llama module is available
36
+ * Check if the native Llama module is available.
37
+ * Uses the singleton getter to avoid creating throwaway HybridObject instances
38
+ * whose C++ destructors could tear down shared bridge state.
25
39
  */
26
40
  export function isNativeLlamaModuleAvailable(): boolean {
27
41
  try {
28
- requireNativeLlamaModule();
42
+ getNativeLlamaModule();
29
43
  return true;
30
44
  } catch {
31
45
  return false;
@@ -1,35 +1,37 @@
1
1
  /**
2
2
  * RunAnywhereLlama Nitrogen Spec
3
3
  *
4
- * LlamaCPP backend interface for Llama-based text generation:
5
- * - Backend Registration
6
- * - Model Loading/Unloading
7
- * - Text Generation (non-streaming and streaming)
8
- * - Structured Output (JSON schema generation)
4
+ * LlamaCPP backend registration hooks.
9
5
  *
10
- * Matches Swift SDK: LlamaCPPRuntime/LlamaCPP.swift + CppBridge+LLM.swift
6
+ * Public lifecycle, generation, structured-output, LoRA, and VLM APIs live in
7
+ * @runanywhere/core and route through commons proto/lifecycle bridges. This
8
+ * backend package only registers native providers.
9
+ *
10
+ * NOTE: After editing this file, run `npx nitro-codegen` (or
11
+ * `yarn llamacpp:nitrogen`) to regenerate the bridge code under
12
+ * `nitrogen/generated/`. Those files are auto-generated and must not be
13
+ * hand-edited; until regeneration they may still reference the removed
14
+ * VLM register/unregister hooks.
11
15
  */
12
16
  import type { HybridObject } from 'react-native-nitro-modules';
13
17
 
14
18
  /**
15
- * Llama text generation native interface
19
+ * LlamaCPP native registration interface.
16
20
  *
17
- * This interface provides Llama-based LLM capabilities.
18
- * Requires @runanywhere/core to be initialized first.
21
+ * The single `registerBackend()` / `unregisterBackend()` pair covers both LLM
22
+ * and VLM modalities the underlying C++ symbol `rac_backend_llamacpp_register()`
23
+ * was unified and the separate `rac_backend_llamacpp_vlm_register()` symbol no
24
+ * longer exists.
19
25
  */
20
26
  export interface RunAnywhereLlama
21
27
  extends HybridObject<{
22
28
  ios: 'c++';
23
29
  android: 'c++';
24
30
  }> {
25
- // ============================================================================
26
- // Backend Registration
27
- // Matches Swift: LlamaCPP.register(), LlamaCPP.unregister()
28
- // ============================================================================
29
-
30
31
  /**
31
32
  * Register the LlamaCPP backend with the C++ service registry.
32
- * Calls rac_backend_llamacpp_register() from runanywhere-binaries.
33
+ * Calls rac_backend_llamacpp_register() from runanywhere-binaries; this
34
+ * single call covers both LLM and VLM modalities.
33
35
  * Safe to call multiple times - subsequent calls are no-ops.
34
36
  * @returns true if registered successfully (or already registered)
35
37
  */
@@ -46,115 +48,4 @@ export interface RunAnywhereLlama
46
48
  * @returns true if backend is registered
47
49
  */
48
50
  isBackendRegistered(): Promise<boolean>;
49
-
50
- // ============================================================================
51
- // Model Loading
52
- // Matches Swift: CppBridge+LLM.swift loadTextModel/unloadTextModel
53
- // ============================================================================
54
-
55
- /**
56
- * Load a Llama model for text generation
57
- * @param path Path to the model file (.gguf)
58
- * @param modelId Optional unique identifier for the model
59
- * @param modelName Optional human-readable name for the model
60
- * @param configJson Optional JSON configuration (context_length, gpu_layers, etc.)
61
- * @returns true if loaded successfully
62
- */
63
- loadModel(
64
- path: string,
65
- modelId?: string,
66
- modelName?: string,
67
- configJson?: string
68
- ): Promise<boolean>;
69
-
70
- /**
71
- * Check if a Llama model is loaded
72
- */
73
- isModelLoaded(): Promise<boolean>;
74
-
75
- /**
76
- * Unload the current Llama model
77
- */
78
- unloadModel(): Promise<boolean>;
79
-
80
- /**
81
- * Get info about the currently loaded model
82
- * @returns JSON with model info or empty if not loaded
83
- */
84
- getModelInfo(): Promise<string>;
85
-
86
- // ============================================================================
87
- // Text Generation
88
- // Matches Swift: RunAnywhere+TextGeneration.swift
89
- // ============================================================================
90
-
91
- /**
92
- * Generate text (non-streaming)
93
- * @param prompt The prompt text
94
- * @param optionsJson JSON string with generation options:
95
- * - max_tokens: Maximum tokens to generate (default: 512)
96
- * - temperature: Sampling temperature (default: 0.7)
97
- * - top_p: Nucleus sampling parameter (default: 0.9)
98
- * - top_k: Top-k sampling parameter (default: 40)
99
- * - system_prompt: Optional system prompt
100
- * @returns JSON string with generation result:
101
- * - text: Generated text
102
- * - tokensUsed: Number of tokens generated
103
- * - latencyMs: Generation time in milliseconds
104
- * - cancelled: Whether generation was cancelled
105
- */
106
- generate(prompt: string, optionsJson?: string): Promise<string>;
107
-
108
- /**
109
- * Generate text with streaming callback
110
- * @param prompt The prompt text
111
- * @param optionsJson JSON string with generation options
112
- * @param callback Called for each token with (token, isComplete)
113
- * @returns Complete generated text
114
- */
115
- generateStream(
116
- prompt: string,
117
- optionsJson: string,
118
- callback: (token: string, isComplete: boolean) => void
119
- ): Promise<string>;
120
-
121
- /**
122
- * Cancel ongoing text generation
123
- * @returns true if cancellation was successful
124
- */
125
- cancelGeneration(): Promise<boolean>;
126
-
127
- // ============================================================================
128
- // Structured Output
129
- // Matches Swift: RunAnywhere+StructuredOutput.swift
130
- // ============================================================================
131
-
132
- /**
133
- * Generate structured output following a JSON schema
134
- * Uses constrained generation to ensure output conforms to schema
135
- * @param prompt The prompt text
136
- * @param schema JSON schema string defining the output structure
137
- * @param optionsJson Optional generation options
138
- * @returns JSON string conforming to the provided schema
139
- */
140
- generateStructured(
141
- prompt: string,
142
- schema: string,
143
- optionsJson?: string
144
- ): Promise<string>;
145
-
146
- // ============================================================================
147
- // Utilities
148
- // ============================================================================
149
-
150
- /**
151
- * Get the last error message from the Llama backend
152
- */
153
- getLastError(): Promise<string>;
154
-
155
- /**
156
- * Get current memory usage of the Llama backend
157
- * @returns Memory usage in bytes
158
- */
159
- getMemoryUsage(): Promise<number>;
160
51
  }
@@ -1,3 +0,0 @@
1
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
- package="com.margelo.nitro.runanywhere.llama">
3
- </manifest>
@@ -1,14 +0,0 @@
1
- /**
2
- * cpp-adapter.cpp
3
- *
4
- * Android JNI entry point for RunAnywhereLlama native module.
5
- * This file is required by React Native's CMake build system.
6
- */
7
-
8
- #include <jni.h>
9
- #include "runanywherellamaOnLoad.hpp"
10
-
11
- extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
12
- // Initialize nitrogen module and register HybridObjects
13
- return margelo::nitro::runanywhere::llama::initialize(vm);
14
- }