@capgo/capacitor-llm 7.1.16 → 7.2.5
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.
- package/Package.swift +0 -4
- package/README.md +33 -1
- package/android/src/main/java/ee/forgr/capgo_llm/LLMPlugin.java +13 -0
- package/dist/docs.json +27 -0
- package/dist/esm/definitions.d.ts +15 -0
- package/dist/esm/definitions.js.map +1 -1
- package/dist/esm/web.d.ts +3 -0
- package/dist/esm/web.js +3 -0
- package/dist/esm/web.js.map +1 -1
- package/dist/plugin.cjs.js +3 -0
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js +3 -0
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/LLMPlugin/LLMPlugin.swift +8 -1
- package/package.json +1 -1
package/Package.swift
CHANGED
|
@@ -11,10 +11,6 @@ let package = Package(
|
|
|
11
11
|
],
|
|
12
12
|
dependencies: [
|
|
13
13
|
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "7.0.0")
|
|
14
|
-
// Note: SwiftTasksVision is for MediaPipe Vision, not GenAI
|
|
15
|
-
// We would need a similar package for MediaPipeTasksGenAI
|
|
16
|
-
// Keeping this as a placeholder for when GenAI SPM support is available
|
|
17
|
-
// .package(url: "https://github.com/paescebu/SwiftTasksVision.git", from: "0.10.21")
|
|
18
14
|
],
|
|
19
15
|
targets: [
|
|
20
16
|
.target(
|
package/README.md
CHANGED
|
@@ -11,6 +11,10 @@ Adds support for LLM locally runned for Capacitor
|
|
|
11
11
|
|
|
12
12
|
It uses Apple Intelligence (default) or MediaPipe custom models on iOS, and MediaPipe's tasks-genai on Android
|
|
13
13
|
|
|
14
|
+
## Documentation
|
|
15
|
+
|
|
16
|
+
The most complete doc is available here: https://capgo.app/docs/plugins/llm/
|
|
17
|
+
|
|
14
18
|
## Installation
|
|
15
19
|
|
|
16
20
|
```bash
|
|
@@ -56,7 +60,19 @@ end
|
|
|
56
60
|
```
|
|
57
61
|
|
|
58
62
|
**Using Swift Package Manager:**
|
|
59
|
-
|
|
63
|
+
|
|
64
|
+
MediaPipe GenAI does not officially support SPM yet (see [MediaPipe issue #5464](https://github.com/google-ai-edge/mediapipe/issues/5464)). However, you can use the community package [SwiftTasksGenAI](https://github.com/paescebu/SwiftTasksGenAI) by adding it manually in Xcode:
|
|
65
|
+
|
|
66
|
+
**To add MediaPipe GenAI via SPM:**
|
|
67
|
+
1. Open your app project in Xcode
|
|
68
|
+
2. Go to **File > Add Package Dependencies...**
|
|
69
|
+
3. Enter the URL: `https://github.com/paescebu/SwiftTasksGenAI.git`
|
|
70
|
+
4. Select your desired version (e.g., 0.10.24)
|
|
71
|
+
5. Add the `SwiftTasksGenAI` product to your app target
|
|
72
|
+
|
|
73
|
+
**Note:** SwiftTasksGenAI uses unsafe build flags, which means it cannot be added directly in Package.swift files, but works fine when added through Xcode's UI. This is the same approach used by SwiftTasksVision.
|
|
74
|
+
|
|
75
|
+
**Alternatively:** Use CocoaPods for a more traditional setup, or use Apple Intelligence (iOS 18.2+) which works with both SPM and CocoaPods.
|
|
60
76
|
|
|
61
77
|
## Adding a Model to Your App
|
|
62
78
|
|
|
@@ -270,6 +286,7 @@ await CapgoLLM.sendMessage({
|
|
|
270
286
|
* [`addListener('aiFinished', ...)`](#addlisteneraifinished-)
|
|
271
287
|
* [`addListener('downloadProgress', ...)`](#addlistenerdownloadprogress-)
|
|
272
288
|
* [`addListener('readinessChange', ...)`](#addlistenerreadinesschange-)
|
|
289
|
+
* [`getPluginVersion()`](#getpluginversion)
|
|
273
290
|
* [Interfaces](#interfaces)
|
|
274
291
|
|
|
275
292
|
</docgen-index>
|
|
@@ -428,6 +445,21 @@ Adds a listener for readiness status changes
|
|
|
428
445
|
--------------------
|
|
429
446
|
|
|
430
447
|
|
|
448
|
+
### getPluginVersion()
|
|
449
|
+
|
|
450
|
+
```typescript
|
|
451
|
+
getPluginVersion() => Promise<{ version: string; }>
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
Get the native Capacitor plugin version.
|
|
455
|
+
|
|
456
|
+
**Returns:** <code>Promise<{ version: string; }></code>
|
|
457
|
+
|
|
458
|
+
**Since:** 1.0.0
|
|
459
|
+
|
|
460
|
+
--------------------
|
|
461
|
+
|
|
462
|
+
|
|
431
463
|
### Interfaces
|
|
432
464
|
|
|
433
465
|
|
|
@@ -9,6 +9,8 @@ import com.getcapacitor.annotation.CapacitorPlugin;
|
|
|
9
9
|
@CapacitorPlugin(name = "CapgoLLM")
|
|
10
10
|
public class LLMPlugin extends Plugin {
|
|
11
11
|
|
|
12
|
+
private final String PLUGIN_VERSION = "7.2.5";
|
|
13
|
+
|
|
12
14
|
private LLM llm;
|
|
13
15
|
|
|
14
16
|
@Override
|
|
@@ -209,4 +211,15 @@ public class LLMPlugin extends Plugin {
|
|
|
209
211
|
interface ProgressCallback {
|
|
210
212
|
void onProgress(int percentage);
|
|
211
213
|
}
|
|
214
|
+
|
|
215
|
+
@PluginMethod
|
|
216
|
+
public void getPluginVersion(final PluginCall call) {
|
|
217
|
+
try {
|
|
218
|
+
final JSObject ret = new JSObject();
|
|
219
|
+
ret.put("version", this.PLUGIN_VERSION);
|
|
220
|
+
call.resolve(ret);
|
|
221
|
+
} catch (final Exception e) {
|
|
222
|
+
call.reject("Could not get plugin version", e);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
212
225
|
}
|
package/dist/docs.json
CHANGED
|
@@ -258,6 +258,33 @@
|
|
|
258
258
|
"ReadinessChangeEvent"
|
|
259
259
|
],
|
|
260
260
|
"slug": "addlistenerreadinesschange-"
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
"name": "getPluginVersion",
|
|
264
|
+
"signature": "() => Promise<{ version: string; }>",
|
|
265
|
+
"parameters": [],
|
|
266
|
+
"returns": "Promise<{ version: string; }>",
|
|
267
|
+
"tags": [
|
|
268
|
+
{
|
|
269
|
+
"name": "returns",
|
|
270
|
+
"text": "Promise that resolves with the plugin version"
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
"name": "throws",
|
|
274
|
+
"text": "Error if getting the version fails"
|
|
275
|
+
},
|
|
276
|
+
{
|
|
277
|
+
"name": "since",
|
|
278
|
+
"text": "1.0.0"
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
"name": "example",
|
|
282
|
+
"text": "```typescript\nconst { version } = await CapgoLLM.getPluginVersion();\nconsole.log('Plugin version:', version);\n```"
|
|
283
|
+
}
|
|
284
|
+
],
|
|
285
|
+
"docs": "Get the native Capacitor plugin version.",
|
|
286
|
+
"complexTypes": [],
|
|
287
|
+
"slug": "getpluginversion"
|
|
261
288
|
}
|
|
262
289
|
],
|
|
263
290
|
"properties": []
|
|
@@ -78,6 +78,21 @@ export interface LLMPlugin {
|
|
|
78
78
|
addListener(eventName: 'readinessChange', listenerFunc: (event: ReadinessChangeEvent) => void): Promise<{
|
|
79
79
|
remove: () => Promise<void>;
|
|
80
80
|
}>;
|
|
81
|
+
/**
|
|
82
|
+
* Get the native Capacitor plugin version.
|
|
83
|
+
*
|
|
84
|
+
* @returns Promise that resolves with the plugin version
|
|
85
|
+
* @throws Error if getting the version fails
|
|
86
|
+
* @since 1.0.0
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* const { version } = await CapgoLLM.getPluginVersion();
|
|
90
|
+
* console.log('Plugin version:', version);
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
getPluginVersion(): Promise<{
|
|
94
|
+
version: string;
|
|
95
|
+
}>;
|
|
81
96
|
}
|
|
82
97
|
/**
|
|
83
98
|
* Event data for text received from AI
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * LLM Plugin interface for interacting with on-device language models\n */\nexport interface LLMPlugin {\n /**\n * Creates a new chat session\n * @returns Promise with chat id and optional instructions\n */\n createChat(): Promise<{ id: string; instructions?: string }>;\n\n /**\n * Sends a message to the AI in a specific chat session\n * @param options - The chat id and message to send\n * @returns Promise that resolves when message is sent\n */\n sendMessage(options: { chatId: string; message: string }): Promise<void>;\n\n /**\n * Gets the readiness status of the LLM\n * @returns Promise with readiness status string\n */\n getReadiness(): Promise<{ readiness: string }>;\n\n /**\n * Sets the model configuration\n * - iOS: Use \"Apple Intelligence\" as path for system model, or provide path to MediaPipe model\n * - Android: Path to a MediaPipe model file (in assets or files directory)\n * @param options - The model configuration\n * @returns Promise that resolves when model is loaded\n */\n setModel(options: ModelOptions): Promise<void>;\n\n /**\n * Downloads a model from a URL and saves it to the appropriate location\n * - iOS: Downloads to the app's documents directory\n * - Android: Downloads to the app's files directory\n * @param options - The download configuration\n * @returns Promise with download result including the saved path\n */\n downloadModel(options: DownloadModelOptions): Promise<DownloadModelResult>;\n\n /**\n * Adds a listener for text received from AI\n * @param eventName - Event name 'textFromAi'\n * @param listenerFunc - Callback function for text events\n * @returns Promise with remove function to unsubscribe\n */\n addListener(\n eventName: 'textFromAi',\n listenerFunc: (event: TextFromAiEvent) => void,\n ): Promise<{ remove: () => Promise<void> }>;\n\n /**\n * Adds a listener for AI completion events\n * @param eventName - Event name 'aiFinished'\n * @param listenerFunc - Callback function for finish events\n * @returns Promise with remove function to unsubscribe\n */\n addListener(\n eventName: 'aiFinished',\n listenerFunc: (event: AiFinishedEvent) => void,\n ): Promise<{ remove: () => Promise<void> }>;\n\n /**\n * Adds a listener for model download progress events\n * @param eventName - Event name 'downloadProgress'\n * @param listenerFunc - Callback function for progress events\n * @returns Promise with remove function to unsubscribe\n */\n addListener(\n eventName: 'downloadProgress',\n listenerFunc: (event: DownloadProgressEvent) => void,\n ): Promise<{ remove: () => Promise<void> }>;\n\n /**\n * Adds a listener for readiness status changes\n * @param eventName - Event name 'readinessChange'\n * @param listenerFunc - Callback function for readiness events\n * @returns Promise with remove function to unsubscribe\n */\n addListener(\n eventName: 'readinessChange',\n listenerFunc: (event: ReadinessChangeEvent) => void,\n ): Promise<{ remove: () => Promise<void> }>;\n}\n\n/**\n * Event data for text received from AI\n */\nexport interface TextFromAiEvent {\n /** The text content from AI - this is an incremental chunk, not the full text */\n text: string;\n /** The chat session ID */\n chatId: string;\n /** Whether this is a complete chunk (true) or partial streaming data (false) */\n isChunk?: boolean;\n}\n\n/**\n * Event data for AI completion\n */\nexport interface AiFinishedEvent {\n /** The chat session ID that finished */\n chatId: string;\n}\n\n/**\n * Options for downloading a model\n */\nexport interface DownloadModelOptions {\n /** URL of the model file to download */\n url: string;\n /** Optional: URL of companion file (e.g., .litertlm for Android) */\n companionUrl?: string;\n /** Optional: Custom filename (defaults to filename from URL) */\n filename?: string;\n}\n\n/**\n * Result of model download\n */\nexport interface DownloadModelResult {\n /** Path where the model was saved */\n path: string;\n /** Path where the companion file was saved (if applicable) */\n companionPath?: string;\n}\n\n/**\n * Event data for download progress\n */\nexport interface DownloadProgressEvent {\n /** Percentage of download completed (0-100) */\n progress: number;\n /** Total bytes to download */\n totalBytes?: number;\n /** Bytes downloaded so far */\n downloadedBytes?: number;\n}\n\n/**\n * Event data for readiness status changes\n */\nexport interface ReadinessChangeEvent {\n /** The readiness status */\n readiness: string;\n}\n\n/**\n * Model configuration options\n */\nexport interface ModelOptions {\n /** Model path or \"Apple Intelligence\" for iOS system model */\n path: string;\n /** Model file type/extension (e.g., \"task\", \"bin\", \"litertlm\"). If not provided, will be extracted from path. */\n modelType?: string;\n /** Maximum number of tokens the model handles */\n maxTokens?: number;\n /** Number of tokens the model considers at each step */\n topk?: number;\n /** Amount of randomness in generation (0.0-1.0) */\n temperature?: number;\n /** Random seed for generation */\n randomSeed?: number;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * LLM Plugin interface for interacting with on-device language models\n */\nexport interface LLMPlugin {\n /**\n * Creates a new chat session\n * @returns Promise with chat id and optional instructions\n */\n createChat(): Promise<{ id: string; instructions?: string }>;\n\n /**\n * Sends a message to the AI in a specific chat session\n * @param options - The chat id and message to send\n * @returns Promise that resolves when message is sent\n */\n sendMessage(options: { chatId: string; message: string }): Promise<void>;\n\n /**\n * Gets the readiness status of the LLM\n * @returns Promise with readiness status string\n */\n getReadiness(): Promise<{ readiness: string }>;\n\n /**\n * Sets the model configuration\n * - iOS: Use \"Apple Intelligence\" as path for system model, or provide path to MediaPipe model\n * - Android: Path to a MediaPipe model file (in assets or files directory)\n * @param options - The model configuration\n * @returns Promise that resolves when model is loaded\n */\n setModel(options: ModelOptions): Promise<void>;\n\n /**\n * Downloads a model from a URL and saves it to the appropriate location\n * - iOS: Downloads to the app's documents directory\n * - Android: Downloads to the app's files directory\n * @param options - The download configuration\n * @returns Promise with download result including the saved path\n */\n downloadModel(options: DownloadModelOptions): Promise<DownloadModelResult>;\n\n /**\n * Adds a listener for text received from AI\n * @param eventName - Event name 'textFromAi'\n * @param listenerFunc - Callback function for text events\n * @returns Promise with remove function to unsubscribe\n */\n addListener(\n eventName: 'textFromAi',\n listenerFunc: (event: TextFromAiEvent) => void,\n ): Promise<{ remove: () => Promise<void> }>;\n\n /**\n * Adds a listener for AI completion events\n * @param eventName - Event name 'aiFinished'\n * @param listenerFunc - Callback function for finish events\n * @returns Promise with remove function to unsubscribe\n */\n addListener(\n eventName: 'aiFinished',\n listenerFunc: (event: AiFinishedEvent) => void,\n ): Promise<{ remove: () => Promise<void> }>;\n\n /**\n * Adds a listener for model download progress events\n * @param eventName - Event name 'downloadProgress'\n * @param listenerFunc - Callback function for progress events\n * @returns Promise with remove function to unsubscribe\n */\n addListener(\n eventName: 'downloadProgress',\n listenerFunc: (event: DownloadProgressEvent) => void,\n ): Promise<{ remove: () => Promise<void> }>;\n\n /**\n * Adds a listener for readiness status changes\n * @param eventName - Event name 'readinessChange'\n * @param listenerFunc - Callback function for readiness events\n * @returns Promise with remove function to unsubscribe\n */\n addListener(\n eventName: 'readinessChange',\n listenerFunc: (event: ReadinessChangeEvent) => void,\n ): Promise<{ remove: () => Promise<void> }>;\n\n /**\n * Get the native Capacitor plugin version.\n *\n * @returns Promise that resolves with the plugin version\n * @throws Error if getting the version fails\n * @since 1.0.0\n * @example\n * ```typescript\n * const { version } = await CapgoLLM.getPluginVersion();\n * console.log('Plugin version:', version);\n * ```\n */\n getPluginVersion(): Promise<{ version: string }>;\n}\n\n/**\n * Event data for text received from AI\n */\nexport interface TextFromAiEvent {\n /** The text content from AI - this is an incremental chunk, not the full text */\n text: string;\n /** The chat session ID */\n chatId: string;\n /** Whether this is a complete chunk (true) or partial streaming data (false) */\n isChunk?: boolean;\n}\n\n/**\n * Event data for AI completion\n */\nexport interface AiFinishedEvent {\n /** The chat session ID that finished */\n chatId: string;\n}\n\n/**\n * Options for downloading a model\n */\nexport interface DownloadModelOptions {\n /** URL of the model file to download */\n url: string;\n /** Optional: URL of companion file (e.g., .litertlm for Android) */\n companionUrl?: string;\n /** Optional: Custom filename (defaults to filename from URL) */\n filename?: string;\n}\n\n/**\n * Result of model download\n */\nexport interface DownloadModelResult {\n /** Path where the model was saved */\n path: string;\n /** Path where the companion file was saved (if applicable) */\n companionPath?: string;\n}\n\n/**\n * Event data for download progress\n */\nexport interface DownloadProgressEvent {\n /** Percentage of download completed (0-100) */\n progress: number;\n /** Total bytes to download */\n totalBytes?: number;\n /** Bytes downloaded so far */\n downloadedBytes?: number;\n}\n\n/**\n * Event data for readiness status changes\n */\nexport interface ReadinessChangeEvent {\n /** The readiness status */\n readiness: string;\n}\n\n/**\n * Model configuration options\n */\nexport interface ModelOptions {\n /** Model path or \"Apple Intelligence\" for iOS system model */\n path: string;\n /** Model file type/extension (e.g., \"task\", \"bin\", \"litertlm\"). If not provided, will be extracted from path. */\n modelType?: string;\n /** Maximum number of tokens the model handles */\n maxTokens?: number;\n /** Number of tokens the model considers at each step */\n topk?: number;\n /** Amount of randomness in generation (0.0-1.0) */\n temperature?: number;\n /** Random seed for generation */\n randomSeed?: number;\n}\n"]}
|
package/dist/esm/web.d.ts
CHANGED
|
@@ -17,4 +17,7 @@ export declare class CapgoLLMWeb extends WebPlugin implements LLMPlugin {
|
|
|
17
17
|
}): Promise<void>;
|
|
18
18
|
setModel(options: ModelOptions): Promise<void>;
|
|
19
19
|
downloadModel(options: DownloadModelOptions): Promise<DownloadModelResult>;
|
|
20
|
+
getPluginVersion(): Promise<{
|
|
21
|
+
version: string;
|
|
22
|
+
}>;
|
|
20
23
|
}
|
package/dist/esm/web.js
CHANGED
package/dist/esm/web.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAmBvE,MAAM,OAAO,WAAY,SAAQ,SAAS;IAA1C;;QACU,QAAG,GAAQ,IAAI,CAAC;QAChB,iBAAY,GAA6B,IAAI,GAAG,EAAE,CAAC;QACnD,cAAS,GAAG,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAmBvE,MAAM,OAAO,WAAY,SAAQ,SAAS;IAA1C;;QACU,QAAG,GAAQ,IAAI,CAAC;QAChB,iBAAY,GAA6B,IAAI,GAAG,EAAE,CAAC;QACnD,cAAS,GAAG,YAAY,CAAC;IA2JnC,CAAC;IAzJC,KAAK,CAAC,YAAY;QAChB,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,UAAU;QACd,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE;YACb,MAAM,IAAI,KAAK,CAAC,wCAAwC,C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AAC,kBAAkB,EAAE;oBACvC,QAAQ;oBACR,UAAU;oBACV,eAAe;iBACS,CAAC,CAAC;aAC7B;YAED,qDAAqD;YACrD,sEAAsE;YACtE,MAAM,MAAM,GAAwB;gBAClC,IAAI,EAAE,OAAO,CAAC,GAAG;aAClB,CAAC;YAEF,oCAAoC;YACpC,IAAI,OAAO,CAAC,YAAY,EAAE;gBACxB,yCAAyC;gBACzC,MAAM,CAAC,aAAa,GAAG,OAAO,CAAC,YAAY,CAAC;aAC7C;YAED,OAAO,MAAM,CAAC;SACf;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;YACjD,MAAM,KAAK,CAAC;SACb;IACH,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { WebPlugin } from '@capacitor/core';\nimport { FilesetResolver, LlmInference } from '@mediapipe/tasks-genai';\n\nimport type {\n LLMPlugin,\n DownloadModelOptions,\n DownloadModelResult,\n ModelOptions,\n TextFromAiEvent,\n AiFinishedEvent,\n DownloadProgressEvent,\n ReadinessChangeEvent,\n} from './definitions';\n\ninterface ChatSession {\n id: string;\n llm: any;\n isActive: boolean;\n}\n\nexport class CapgoLLMWeb extends WebPlugin implements LLMPlugin {\n private llm: any = null;\n private chatSessions: Map<string, ChatSession> = new Map();\n private readiness = 'not-loaded';\n\n async getReadiness(): Promise<{ readiness: string }> {\n return { readiness: this.readiness };\n }\n\n async createChat(): Promise<{ id: string; instructions?: string }> {\n if (!this.llm) {\n throw new Error('Model not loaded. Call setModel first.');\n }\n\n const chatId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n this.chatSessions.set(chatId, {\n id: chatId,\n llm: this.llm,\n isActive: true,\n });\n\n return { id: chatId };\n }\n\n async sendMessage(options: { chatId: string; message: string }): Promise<void> {\n const session = this.chatSessions.get(options.chatId);\n if (!session) {\n throw new Error(`Chat session ${options.chatId} not found`);\n }\n\n if (!session.isActive) {\n throw new Error(`Chat session ${options.chatId} is not active`);\n }\n\n try {\n // Generate response using MediaPipe GenAI streaming API\n const response = session.llm.generateResponseStream(options.message);\n\n for await (const partialResponse of response) {\n // Send incremental text\n this.notifyListeners('textFromAi', {\n text: partialResponse,\n chatId: options.chatId,\n isChunk: true,\n } as TextFromAiEvent);\n }\n\n // Notify completion\n this.notifyListeners('aiFinished', {\n chatId: options.chatId,\n } as AiFinishedEvent);\n } catch (error) {\n console.error('Error generating response:', error);\n throw error;\n }\n }\n\n async setModel(options: ModelOptions): Promise<void> {\n try {\n // Update readiness\n this.readiness = 'loading';\n this.notifyListeners('readinessChange', { readiness: this.readiness } as ReadinessChangeEvent);\n\n // Create LLM configuration\n const config: any = {\n baseOptions: {\n modelAssetPath: options.path,\n },\n maxTokens: options.maxTokens || 2048,\n topK: options.topk || 40,\n temperature: options.temperature || 0.8,\n randomSeed: options.randomSeed || 0,\n };\n\n const genai = await FilesetResolver.forGenAiTasks(\n 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-genai@latest/wasm',\n );\n // Create LLM instance\n this.llm = await LlmInference.createFromOptions(genai, config);\n\n // Update readiness\n this.readiness = 'ready';\n this.notifyListeners('readinessChange', { readiness: this.readiness } as ReadinessChangeEvent);\n } catch (error) {\n this.readiness = 'error';\n this.notifyListeners('readinessChange', { readiness: this.readiness } as ReadinessChangeEvent);\n throw error;\n }\n }\n\n async downloadModel(options: DownloadModelOptions): Promise<DownloadModelResult> {\n try {\n // For web, we'll simulate download by fetching and storing in IndexedDB or returning the URL\n const response = await fetch(options.url, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/octet-stream',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to download model: ${response.statusText}`);\n }\n\n const contentLength = response.headers.get('content-length');\n const totalBytes = contentLength ? parseInt(contentLength, 10) : undefined;\n\n // Read the response with progress\n const reader = response.body?.getReader();\n if (!reader) {\n throw new Error('Failed to get reader from response');\n }\n\n const chunks: Uint8Array[] = [];\n let downloadedBytes = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) break;\n\n if (value) {\n chunks.push(value);\n downloadedBytes += value.length;\n }\n\n // Notify progress\n const progress = totalBytes ? (downloadedBytes / totalBytes) * 100 : 0;\n this.notifyListeners('downloadProgress', {\n progress,\n totalBytes,\n downloadedBytes,\n } as DownloadProgressEvent);\n }\n\n // For web, we'll return the original URL as the path\n // In a real implementation, you might want to store this in IndexedDB\n const result: DownloadModelResult = {\n path: options.url,\n };\n\n // Handle companion file if provided\n if (options.companionUrl) {\n // For web, just return the companion URL\n result.companionPath = options.companionUrl;\n }\n\n return result;\n } catch (error) {\n console.error('Error downloading model:', error);\n throw error;\n }\n }\n\n async getPluginVersion(): Promise<{ version: string }> {\n return { version: 'web' };\n }\n}\n"]}
|
package/dist/plugin.cjs.js
CHANGED
package/dist/plugin.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst CapgoLLM = registerPlugin('CapgoLLM', {\n web: () => import('./web').then((m) => new m.CapgoLLMWeb()),\n});\nexport * from './definitions';\nexport { CapgoLLM };\n//# sourceMappingURL=index.js.map","var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nimport { WebPlugin } from '@capacitor/core';\nimport { FilesetResolver, LlmInference } from '@mediapipe/tasks-genai';\nexport class CapgoLLMWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.llm = null;\n this.chatSessions = new Map();\n this.readiness = 'not-loaded';\n }\n async getReadiness() {\n return { readiness: this.readiness };\n }\n async createChat() {\n if (!this.llm) {\n throw new Error('Model not loaded. Call setModel first.');\n }\n const chatId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.chatSessions.set(chatId, {\n id: chatId,\n llm: this.llm,\n isActive: true,\n });\n return { id: chatId };\n }\n async sendMessage(options) {\n var e_1, _a;\n const session = this.chatSessions.get(options.chatId);\n if (!session) {\n throw new Error(`Chat session ${options.chatId} not found`);\n }\n if (!session.isActive) {\n throw new Error(`Chat session ${options.chatId} is not active`);\n }\n try {\n // Generate response using MediaPipe GenAI streaming API\n const response = session.llm.generateResponseStream(options.message);\n try {\n for (var response_1 = __asyncValues(response), response_1_1; response_1_1 = await response_1.next(), !response_1_1.done;) {\n const partialResponse = response_1_1.value;\n // Send incremental text\n this.notifyListeners('textFromAi', {\n text: partialResponse,\n chatId: options.chatId,\n isChunk: true,\n });\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (response_1_1 && !response_1_1.done && (_a = response_1.return)) await _a.call(response_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Notify completion\n this.notifyListeners('aiFinished', {\n chatId: options.chatId,\n });\n }\n catch (error) {\n console.error('Error generating response:', error);\n throw error;\n }\n }\n async setModel(options) {\n try {\n // Update readiness\n this.readiness = 'loading';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n // Create LLM configuration\n const config = {\n baseOptions: {\n modelAssetPath: options.path,\n },\n maxTokens: options.maxTokens || 2048,\n topK: options.topk || 40,\n temperature: options.temperature || 0.8,\n randomSeed: options.randomSeed || 0,\n };\n const genai = await FilesetResolver.forGenAiTasks('https://cdn.jsdelivr.net/npm/@mediapipe/tasks-genai@latest/wasm');\n // Create LLM instance\n this.llm = await LlmInference.createFromOptions(genai, config);\n // Update readiness\n this.readiness = 'ready';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n }\n catch (error) {\n this.readiness = 'error';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n throw error;\n }\n }\n async downloadModel(options) {\n var _a;\n try {\n // For web, we'll simulate download by fetching and storing in IndexedDB or returning the URL\n const response = await fetch(options.url, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/octet-stream',\n },\n });\n if (!response.ok) {\n throw new Error(`Failed to download model: ${response.statusText}`);\n }\n const contentLength = response.headers.get('content-length');\n const totalBytes = contentLength ? parseInt(contentLength, 10) : undefined;\n // Read the response with progress\n const reader = (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader();\n if (!reader) {\n throw new Error('Failed to get reader from response');\n }\n const chunks = [];\n let downloadedBytes = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n if (value) {\n chunks.push(value);\n downloadedBytes += value.length;\n }\n // Notify progress\n const progress = totalBytes ? (downloadedBytes / totalBytes) * 100 : 0;\n this.notifyListeners('downloadProgress', {\n progress,\n totalBytes,\n downloadedBytes,\n });\n }\n // For web, we'll return the original URL as the path\n // In a real implementation, you might want to store this in IndexedDB\n const result = {\n path: options.url,\n };\n // Handle companion file if provided\n if (options.companionUrl) {\n // For web, just return the companion URL\n result.companionPath = options.companionUrl;\n }\n return result;\n }\n catch (error) {\n console.error('Error downloading model:', error);\n throw error;\n }\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","this","WebPlugin","FilesetResolver","LlmInference"],"mappings":";;;;;AACK,MAAC,QAAQ,GAAGA,mBAAc,CAAC,UAAU,EAAE;AAC5C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;AAC/D,CAAC;;ACHD,IAAI,aAAa,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AC,IAAI,EAAE;AAC3D,gBAAgB,IAAI,IAAI;AACxB,oBAAoB;AACpB,gBAAgB,IAAI,KAAK,EAAE;AAC3B,oBAAoB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC;AACtC,oBAAoB,eAAe,IAAI,KAAK,CAAC,MAAM;AACnD,gBAAgB;AAChB;AACA,gBAAgB,MAAM,QAAQ,GAAG,UAAU,GAAG,CAAC,eAAe,GAAG,UAAU,IAAI,GAAG,GAAG,CAAC;AACtF,gBAAgB,IAAI,CAAC,eAAe,CAAC,kBAAkB,EAAE;AACzD,oBAAoB,QAAQ;AAC5B,oBAAoB,UAAU;AAC9B,oBAAoB,eAAe;AACnC,iBAAiB,CAAC;AAClB,YAAY;AACZ;AACA;AACA,YAAY,MAAM,MAAM,GAAG;AAC3B,gBAAgB,IAAI,EAAE,OAAO,CAAC,GAAG;AACjC,aAAa;AACb;AACA,YAAY,IAAI,OAAO,CAAC,YAAY,EAAE;AACtC;AACA,gBAAgB,MAAM,CAAC,aAAa,GAAG,OAAO,CAAC,YAAY;AAC3D,YAAY;AACZ,YAAY,OAAO,MAAM;AACzB,QAAQ;AACR,QAAQ,OAAO,KAAK,EAAE;AACtB,YAAY,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC;AAC5D,YAAY,MAAM,KAAK;AACvB,QAAQ;AACR,IAAI;AACJ;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst CapgoLLM = registerPlugin('CapgoLLM', {\n web: () => import('./web').then((m) => new m.CapgoLLMWeb()),\n});\nexport * from './definitions';\nexport { CapgoLLM };\n//# sourceMappingURL=index.js.map","var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nimport { WebPlugin } from '@capacitor/core';\nimport { FilesetResolver, LlmInference } from '@mediapipe/tasks-genai';\nexport class CapgoLLMWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.llm = null;\n this.chatSessions = new Map();\n this.readiness = 'not-loaded';\n }\n async getReadiness() {\n return { readiness: this.readiness };\n }\n async createChat() {\n if (!this.llm) {\n throw new Error('Model not loaded. Call setModel first.');\n }\n const chatId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.chatSessions.set(chatId, {\n id: chatId,\n llm: this.llm,\n isActive: true,\n });\n return { id: chatId };\n }\n async sendMessage(options) {\n var e_1, _a;\n const session = this.chatSessions.get(options.chatId);\n if (!session) {\n throw new Error(`Chat session ${options.chatId} not found`);\n }\n if (!session.isActive) {\n throw new Error(`Chat session ${options.chatId} is not active`);\n }\n try {\n // Generate response using MediaPipe GenAI streaming API\n const response = session.llm.generateResponseStream(options.message);\n try {\n for (var response_1 = __asyncValues(response), response_1_1; response_1_1 = await response_1.next(), !response_1_1.done;) {\n const partialResponse = response_1_1.value;\n // Send incremental text\n this.notifyListeners('textFromAi', {\n text: partialResponse,\n chatId: options.chatId,\n isChunk: true,\n });\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (response_1_1 && !response_1_1.done && (_a = response_1.return)) await _a.call(response_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Notify completion\n this.notifyListeners('aiFinished', {\n chatId: options.chatId,\n });\n }\n catch (error) {\n console.error('Error generating response:', error);\n throw error;\n }\n }\n async setModel(options) {\n try {\n // Update readiness\n this.readiness = 'loading';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n // Create LLM configuration\n const config = {\n baseOptions: {\n modelAssetPath: options.path,\n },\n maxTokens: options.maxTokens || 2048,\n topK: options.topk || 40,\n temperature: options.temperature || 0.8,\n randomSeed: options.randomSeed || 0,\n };\n const genai = await FilesetResolver.forGenAiTasks('https://cdn.jsdelivr.net/npm/@mediapipe/tasks-genai@latest/wasm');\n // Create LLM instance\n this.llm = await LlmInference.createFromOptions(genai, config);\n // Update readiness\n this.readiness = 'ready';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n }\n catch (error) {\n this.readiness = 'error';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n throw error;\n }\n }\n async downloadModel(options) {\n var _a;\n try {\n // For web, we'll simulate download by fetching and storing in IndexedDB or returning the URL\n const response = await fetch(options.url, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/octet-stream',\n },\n });\n if (!response.ok) {\n throw new Error(`Failed to download model: ${response.statusText}`);\n }\n const contentLength = response.headers.get('content-length');\n const totalBytes = contentLength ? parseInt(contentLength, 10) : undefined;\n // Read the response with progress\n const reader = (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader();\n if (!reader) {\n throw new Error('Failed to get reader from response');\n }\n const chunks = [];\n let downloadedBytes = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n if (value) {\n chunks.push(value);\n downloadedBytes += value.length;\n }\n // Notify progress\n const progress = totalBytes ? (downloadedBytes / totalBytes) * 100 : 0;\n this.notifyListeners('downloadProgress', {\n progress,\n totalBytes,\n downloadedBytes,\n });\n }\n // For web, we'll return the original URL as the path\n // In a real implementation, you might want to store this in IndexedDB\n const result = {\n path: options.url,\n };\n // Handle companion file if provided\n if (options.companionUrl) {\n // For web, just return the companion URL\n result.companionPath = options.companionUrl;\n }\n return result;\n }\n catch (error) {\n console.error('Error downloading model:', error);\n throw error;\n }\n }\n async getPluginVersion() {\n return { version: 'web' };\n }\n}\n//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package/dist/plugin.js
CHANGED
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst CapgoLLM = registerPlugin('CapgoLLM', {\n web: () => import('./web').then((m) => new m.CapgoLLMWeb()),\n});\nexport * from './definitions';\nexport { CapgoLLM };\n//# sourceMappingURL=index.js.map","var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nimport { WebPlugin } from '@capacitor/core';\nimport { FilesetResolver, LlmInference } from '@mediapipe/tasks-genai';\nexport class CapgoLLMWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.llm = null;\n this.chatSessions = new Map();\n this.readiness = 'not-loaded';\n }\n async getReadiness() {\n return { readiness: this.readiness };\n }\n async createChat() {\n if (!this.llm) {\n throw new Error('Model not loaded. Call setModel first.');\n }\n const chatId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.chatSessions.set(chatId, {\n id: chatId,\n llm: this.llm,\n isActive: true,\n });\n return { id: chatId };\n }\n async sendMessage(options) {\n var e_1, _a;\n const session = this.chatSessions.get(options.chatId);\n if (!session) {\n throw new Error(`Chat session ${options.chatId} not found`);\n }\n if (!session.isActive) {\n throw new Error(`Chat session ${options.chatId} is not active`);\n }\n try {\n // Generate response using MediaPipe GenAI streaming API\n const response = session.llm.generateResponseStream(options.message);\n try {\n for (var response_1 = __asyncValues(response), response_1_1; response_1_1 = await response_1.next(), !response_1_1.done;) {\n const partialResponse = response_1_1.value;\n // Send incremental text\n this.notifyListeners('textFromAi', {\n text: partialResponse,\n chatId: options.chatId,\n isChunk: true,\n });\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (response_1_1 && !response_1_1.done && (_a = response_1.return)) await _a.call(response_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Notify completion\n this.notifyListeners('aiFinished', {\n chatId: options.chatId,\n });\n }\n catch (error) {\n console.error('Error generating response:', error);\n throw error;\n }\n }\n async setModel(options) {\n try {\n // Update readiness\n this.readiness = 'loading';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n // Create LLM configuration\n const config = {\n baseOptions: {\n modelAssetPath: options.path,\n },\n maxTokens: options.maxTokens || 2048,\n topK: options.topk || 40,\n temperature: options.temperature || 0.8,\n randomSeed: options.randomSeed || 0,\n };\n const genai = await FilesetResolver.forGenAiTasks('https://cdn.jsdelivr.net/npm/@mediapipe/tasks-genai@latest/wasm');\n // Create LLM instance\n this.llm = await LlmInference.createFromOptions(genai, config);\n // Update readiness\n this.readiness = 'ready';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n }\n catch (error) {\n this.readiness = 'error';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n throw error;\n }\n }\n async downloadModel(options) {\n var _a;\n try {\n // For web, we'll simulate download by fetching and storing in IndexedDB or returning the URL\n const response = await fetch(options.url, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/octet-stream',\n },\n });\n if (!response.ok) {\n throw new Error(`Failed to download model: ${response.statusText}`);\n }\n const contentLength = response.headers.get('content-length');\n const totalBytes = contentLength ? parseInt(contentLength, 10) : undefined;\n // Read the response with progress\n const reader = (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader();\n if (!reader) {\n throw new Error('Failed to get reader from response');\n }\n const chunks = [];\n let downloadedBytes = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n if (value) {\n chunks.push(value);\n downloadedBytes += value.length;\n }\n // Notify progress\n const progress = totalBytes ? (downloadedBytes / totalBytes) * 100 : 0;\n this.notifyListeners('downloadProgress', {\n progress,\n totalBytes,\n downloadedBytes,\n });\n }\n // For web, we'll return the original URL as the path\n // In a real implementation, you might want to store this in IndexedDB\n const result = {\n path: options.url,\n };\n // Handle companion file if provided\n if (options.companionUrl) {\n // For web, just return the companion URL\n result.companionPath = options.companionUrl;\n }\n return result;\n }\n catch (error) {\n console.error('Error downloading model:', error);\n throw error;\n }\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","this","WebPlugin","FilesetResolver","LlmInference"],"mappings":";;;AACK,UAAC,QAAQ,GAAGA,mBAAc,CAAC,UAAU,EAAE;IAC5C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;IAC/D,CAAC;;ICHD,IAAI,aAAa,GAAG,CAACC,UAAI,IAAIA,UAAI,CAAC,aAAa,KAAK,UAAU,CAAC,EAAE;IACjE,IAAI,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE,MAAM,IAAI,SAAS,CAAC,sCAAsC,CAAC;IAC1F,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;IACtC,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,QAAQ,KAAK,UAAU,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,aAAa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,CAAC,YAAY,EAAE;IACtC;IACA,gBAAgB,MAAM,CAAC,aAAa,GAAG,OAAO,CAAC,YAAY;IAC3D,YAAY;IACZ,YAAY,OAAO,MAAM;IACzB,QAAQ;IACR,QAAQ,OAAO,KAAK,EAAE;IACtB,YAAY,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC;IAC5D,YAAY,MAAM,KAAK;IACvB,QAAQ;IACR,IAAI;IACJ;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst CapgoLLM = registerPlugin('CapgoLLM', {\n web: () => import('./web').then((m) => new m.CapgoLLMWeb()),\n});\nexport * from './definitions';\nexport { CapgoLLM };\n//# sourceMappingURL=index.js.map","var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nimport { WebPlugin } from '@capacitor/core';\nimport { FilesetResolver, LlmInference } from '@mediapipe/tasks-genai';\nexport class CapgoLLMWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.llm = null;\n this.chatSessions = new Map();\n this.readiness = 'not-loaded';\n }\n async getReadiness() {\n return { readiness: this.readiness };\n }\n async createChat() {\n if (!this.llm) {\n throw new Error('Model not loaded. Call setModel first.');\n }\n const chatId = `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.chatSessions.set(chatId, {\n id: chatId,\n llm: this.llm,\n isActive: true,\n });\n return { id: chatId };\n }\n async sendMessage(options) {\n var e_1, _a;\n const session = this.chatSessions.get(options.chatId);\n if (!session) {\n throw new Error(`Chat session ${options.chatId} not found`);\n }\n if (!session.isActive) {\n throw new Error(`Chat session ${options.chatId} is not active`);\n }\n try {\n // Generate response using MediaPipe GenAI streaming API\n const response = session.llm.generateResponseStream(options.message);\n try {\n for (var response_1 = __asyncValues(response), response_1_1; response_1_1 = await response_1.next(), !response_1_1.done;) {\n const partialResponse = response_1_1.value;\n // Send incremental text\n this.notifyListeners('textFromAi', {\n text: partialResponse,\n chatId: options.chatId,\n isChunk: true,\n });\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (response_1_1 && !response_1_1.done && (_a = response_1.return)) await _a.call(response_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Notify completion\n this.notifyListeners('aiFinished', {\n chatId: options.chatId,\n });\n }\n catch (error) {\n console.error('Error generating response:', error);\n throw error;\n }\n }\n async setModel(options) {\n try {\n // Update readiness\n this.readiness = 'loading';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n // Create LLM configuration\n const config = {\n baseOptions: {\n modelAssetPath: options.path,\n },\n maxTokens: options.maxTokens || 2048,\n topK: options.topk || 40,\n temperature: options.temperature || 0.8,\n randomSeed: options.randomSeed || 0,\n };\n const genai = await FilesetResolver.forGenAiTasks('https://cdn.jsdelivr.net/npm/@mediapipe/tasks-genai@latest/wasm');\n // Create LLM instance\n this.llm = await LlmInference.createFromOptions(genai, config);\n // Update readiness\n this.readiness = 'ready';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n }\n catch (error) {\n this.readiness = 'error';\n this.notifyListeners('readinessChange', { readiness: this.readiness });\n throw error;\n }\n }\n async downloadModel(options) {\n var _a;\n try {\n // For web, we'll simulate download by fetching and storing in IndexedDB or returning the URL\n const response = await fetch(options.url, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/octet-stream',\n },\n });\n if (!response.ok) {\n throw new Error(`Failed to download model: ${response.statusText}`);\n }\n const contentLength = response.headers.get('content-length');\n const totalBytes = contentLength ? parseInt(contentLength, 10) : undefined;\n // Read the response with progress\n const reader = (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader();\n if (!reader) {\n throw new Error('Failed to get reader from response');\n }\n const chunks = [];\n let downloadedBytes = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n if (value) {\n chunks.push(value);\n downloadedBytes += value.length;\n }\n // Notify progress\n const progress = totalBytes ? (downloadedBytes / totalBytes) * 100 : 0;\n this.notifyListeners('downloadProgress', {\n progress,\n totalBytes,\n downloadedBytes,\n });\n }\n // For web, we'll return the original URL as the path\n // In a real implementation, you might want to store this in IndexedDB\n const result = {\n path: options.url,\n };\n // Handle companion file if provided\n if (options.companionUrl) {\n // For web, just return the companion URL\n result.companionPath = options.companionUrl;\n }\n return result;\n }\n catch (error) {\n console.error('Error downloading model:', error);\n throw error;\n }\n }\n async getPluginVersion() {\n return { version: 'web' };\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","this","WebPlugin","FilesetResolver","LlmInference"],"mappings":";;;AACK,UAAC,QAAQ,GAAGA,mBAAc,CAAC,UAAU,EAAE;IAC5C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;IAC/D,CAAC;;ICHD,IAAI,aAAa,GAAG,CAACC,UAAI,IAAIA,UAAI,CAAC,aAAa,KAAK,UAAU,CAAC,EAAE;IACjE,IAAI,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE,MAAM,IAAI,SAAS,CAAC,sCAAsC,CAAC;IAC1F,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;IACtC,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,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gBAAgB,IAAI,CAAC,eAAe,CAAC,kBAAkB,EAAE;IACzD,oBAAoB,QAAQ;IAC5B,oBAAoB,UAAU;IAC9B,oBAAoB,eAAe;IACnC,iBAAiB,CAAC;IAClB,YAAY;IACZ;IACA;IACA,YAAY,MAAM,MAAM,GAAG;IAC3B,gBAAgB,IAAI,EAAE,OAAO,CAAC,GAAG;IACjC,aAAa;IACb;IACA,YAAY,IAAI,OAAO,CAAC,YAAY,EAAE;IACtC;IACA,gBAAgB,MAAM,CAAC,aAAa,GAAG,OAAO,CAAC,YAAY;IAC3D,YAAY;IACZ,YAAY,OAAO,MAAM;IACzB,QAAQ;IACR,QAAQ,OAAO,KAAK,EAAE;IACtB,YAAY,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC;IAC5D,YAAY,MAAM,KAAK;IACvB,QAAQ;IACR,IAAI;IACJ,IAAI,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE;IACjC,IAAI;IACJ;;;;;;;;;;;;;;;"}
|
|
@@ -16,6 +16,7 @@ import MediaPipeTasksGenAI
|
|
|
16
16
|
|
|
17
17
|
@objc(LLMPlugin)
|
|
18
18
|
public class LLMPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
19
|
+
private let PLUGIN_VERSION: String = "7.2.5"
|
|
19
20
|
public let identifier = "LLMPlugin"
|
|
20
21
|
public let jsName = "CapgoLLM"
|
|
21
22
|
public var pluginMethods: [CAPPluginMethod] = [
|
|
@@ -23,7 +24,8 @@ public class LLMPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
|
23
24
|
CAPPluginMethod(name: "sendMessage", returnType: CAPPluginReturnPromise),
|
|
24
25
|
CAPPluginMethod(name: "getReadiness", returnType: CAPPluginReturnPromise),
|
|
25
26
|
CAPPluginMethod(name: "setModel", returnType: CAPPluginReturnPromise),
|
|
26
|
-
CAPPluginMethod(name: "downloadModel", returnType: CAPPluginReturnPromise)
|
|
27
|
+
CAPPluginMethod(name: "downloadModel", returnType: CAPPluginReturnPromise),
|
|
28
|
+
CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise)
|
|
27
29
|
]
|
|
28
30
|
|
|
29
31
|
private enum ModelType {
|
|
@@ -437,6 +439,10 @@ public class LLMPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
|
437
439
|
|
|
438
440
|
downloadTask.resume()
|
|
439
441
|
}
|
|
442
|
+
|
|
443
|
+
@objc func getPluginVersion(_ call: CAPPluginCall) {
|
|
444
|
+
call.resolve(["version": self.PLUGIN_VERSION])
|
|
445
|
+
}
|
|
440
446
|
}
|
|
441
447
|
|
|
442
448
|
// Download delegate class to handle progress updates
|
|
@@ -466,4 +472,5 @@ class DownloadDelegate: NSObject, URLSessionDownloadDelegate {
|
|
|
466
472
|
didFinishDownloadingTo location: URL) {
|
|
467
473
|
// Handled in the completion handler
|
|
468
474
|
}
|
|
475
|
+
|
|
469
476
|
}
|