catalyst-ai 0.1.1 → 1.0.1-canary.2
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/README.md +43 -70
- package/android/src/main/java/io/catalyst/nativeai/NativeBridgeAI.kt +4 -2
- package/package.json +16 -2
- package/plugins/ai/LiteRTLM/LICENSE +201 -0
- package/plugins/ai/LiteRTLM/Package.swift +28 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/Benchmark.swift +91 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/Capabilities.swift +114 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/Config.swift +327 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/Conversation.swift +844 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/EmbeddingEngine.swift +355 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/EmbeddingEngineConfig.swift +105 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/Engine.swift +307 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/ExperimentalFlags.swift +207 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/LiteRTLMError.swift +216 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/Message.swift +278 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/ResponseFormat.swift +72 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/Tool.swift +291 -0
- package/plugins/ai/LiteRTLM/Sources/LiteRTLM/ToolManager.swift +152 -0
- package/plugins/ai/LiteRTLM/VENDORED.md +9 -0
- package/plugins/ai/ios/AIBridge.swift +45 -0
- package/plugins/ai/ios/CatalystAIBridge.swift +148 -0
- package/plugins/ai/ios/CatalystAIPlugin.swift +104 -0
- package/plugins/ai/ios/FoundationModelsAI.swift +144 -0
- package/plugins/ai/ios/NativeBridgeAI.swift +312 -0
- package/plugins/ai/ios/Support/AIOptions.swift +40 -0
- package/plugins/ai/ios/Support/AIPromptBuilder.swift +41 -0
- package/plugins/ai/ios/Support/EngineSelection.swift +38 -0
- package/plugins/ai/ios/Support/FoundationModelsErrors.swift +30 -0
- package/plugins/ai/ios/Support/ProgressThrottle.swift +27 -0
- package/plugins/ai/ios/Support/StreamDelta.swift +29 -0
- package/plugins/ai/manifest.json +30 -0
- package/plugins/ai/scripts/vendor-litertlm.sh +29 -0
- package/src/index.js +1 -0
- package/src/nativeTransport.js +89 -0
- package/src/route.d.ts +88 -0
- package/src/route.js +118 -20
- package/src/useNativeAI.js +109 -48
- package/src/useWebAI.js +7 -3
package/README.md
CHANGED
|
@@ -3,76 +3,6 @@
|
|
|
3
3
|
Multi-provider AI integration for catalyst-core apps — OpenAI/Gemini SSE routes plus
|
|
4
4
|
`useCloudAI`, `useWebAI`, and `useNativeAI` React hooks.
|
|
5
5
|
|
|
6
|
-
> **Requires `catalyst-core` as a peer dependency.** This package does not work standalone —
|
|
7
|
-
> `catalyst-core`'s `useAI` hook loads it via `require("catalyst-ai")` at runtime, and its
|
|
8
|
-
> Express router is meant to be mounted by `catalyst-core`'s server. See `peerDependencies` in
|
|
9
|
-
> `package.json` for the minimum compatible `catalyst-core` version.
|
|
10
|
-
|
|
11
|
-
## Install
|
|
12
|
-
|
|
13
|
-
```bash
|
|
14
|
-
npm install catalyst-ai
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
`catalyst-core` must already be installed in the app (`>=0.3.0-0`, per this package's
|
|
18
|
-
`peerDependencies`) — install will fail its `preinstall` peer check otherwise.
|
|
19
|
-
|
|
20
|
-
## Usage
|
|
21
|
-
|
|
22
|
-
### 1. Configure the server (`AI_CONFIG` env var)
|
|
23
|
-
|
|
24
|
-
`catalyst-core`'s `expressServer.js` auto-mounts this package's router when it's installed and
|
|
25
|
-
`AI_CONFIG.enabled` is `true`. Set `AI_CONFIG` as a JSON string in your app's environment:
|
|
26
|
-
|
|
27
|
-
```json
|
|
28
|
-
{
|
|
29
|
-
"enabled": true,
|
|
30
|
-
"basePath": "/ai",
|
|
31
|
-
"providers": {
|
|
32
|
-
"openai": { "apiKey": "sk-...", "model": "gpt-5" },
|
|
33
|
-
"gemini": { "apiKey": "...", "model": "gemini-2.5-flash" }
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
No `providers.<name>.apiKey` means that provider's routes are disabled. See the **Security**
|
|
39
|
-
section below before exposing `/ai/*` beyond a trusted internal network.
|
|
40
|
-
|
|
41
|
-
### 2. Call the hook from a component
|
|
42
|
-
|
|
43
|
-
Prefer `catalyst-core`'s `useAI` — it picks the right sub-hook (`useCloudAI` / `useWebAI` /
|
|
44
|
-
`useNativeAI`) based on `options.provider`:
|
|
45
|
-
|
|
46
|
-
```jsx
|
|
47
|
-
import { useAI } from "catalyst-core/hooks"
|
|
48
|
-
|
|
49
|
-
function Chat() {
|
|
50
|
-
const { output, streaming, generate, cancel, error } = useAI({
|
|
51
|
-
provider: "openai", // "openai" | "gemini" → cloud, "transformers" → web, "native" → native
|
|
52
|
-
systemPrompt: "You are a helpful assistant.",
|
|
53
|
-
})
|
|
54
|
-
|
|
55
|
-
return (
|
|
56
|
-
<div>
|
|
57
|
-
<button onClick={() => generate("Hello!")} disabled={streaming}>Send</button>
|
|
58
|
-
<p>{output}</p>
|
|
59
|
-
</div>
|
|
60
|
-
)
|
|
61
|
-
}
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
Or import a specific hook directly from `catalyst-ai` if you don't need provider auto-routing:
|
|
65
|
-
|
|
66
|
-
```jsx
|
|
67
|
-
import { useCloudAI } from "catalyst-ai"
|
|
68
|
-
|
|
69
|
-
const { output, streaming, generate, cancel, error } = useCloudAI({
|
|
70
|
-
basePath: "/ai", // must match AI_CONFIG.basePath
|
|
71
|
-
provider: "openai", // or "gemini"
|
|
72
|
-
sessionMode: "stateless", // or "stateful"
|
|
73
|
-
})
|
|
74
|
-
```
|
|
75
|
-
|
|
76
6
|
## Security: authentication and rate limiting
|
|
77
7
|
|
|
78
8
|
The Express router exposed by this package (`src/route.js`, mounted at `AI_CONFIG.basePath`
|
|
@@ -98,3 +28,46 @@ third-party code fetched over the network at runtime. If your app has a Content-
|
|
|
98
28
|
you'll need to allow `https://cdn.jsdelivr.net` for `worker-src`/`script-src`, or fork this
|
|
99
29
|
provider to bundle the library instead. Treat `useWebAI` as a demo/fallback path, not
|
|
100
30
|
production-ready, per the EXPERIMENTAL note in its source.
|
|
31
|
+
|
|
32
|
+
## Native AI on iOS
|
|
33
|
+
|
|
34
|
+
`useNativeAI` (and `useAI({ provider: "native" })`) also runs on-device on iOS. Set
|
|
35
|
+
`ai.enabled: true` in `WEBVIEW_CONFIG`, install `catalyst-ai` in the app, and build the iOS app as usual.
|
|
36
|
+
The build then adds this package's `plugins/ai` module, the LiteRT-LM Swift package, and the
|
|
37
|
+
`com.apple.developer.kernel.increased-memory-limit` entitlement. None of this happens unless
|
|
38
|
+
`ai.enabled` is true: installing `catalyst-ai` alone adds nothing to the iOS build. The LiteRT-LM Swift wrapper
|
|
39
|
+
is vendored (`plugins/ai/LiteRTLM`), so no Git LFS or large clone is needed.
|
|
40
|
+
|
|
41
|
+
**Requirements**
|
|
42
|
+
|
|
43
|
+
- Apple Silicon Mac for the simulator (the LiteRT-LM binary has no Intel simulator slice).
|
|
44
|
+
- Adds roughly 120 MB (the LiteRT-LM framework, downloaded once by SwiftPM) to the app binary.
|
|
45
|
+
- On a device, the **Increased Memory Limit** capability must be allowed for your App ID, or signing fails.
|
|
46
|
+
|
|
47
|
+
**Engines.** Two on-device engines sit behind the same hook, chosen when `initAI` runs (`engine` option):
|
|
48
|
+
|
|
49
|
+
| `engine` | Behaviour |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `"auto"` (default) | LiteRT-LM if its model is already downloaded; otherwise Apple Foundation Models if available; otherwise LiteRT-LM, which downloads the model first. |
|
|
52
|
+
| `"litert"` | LiteRT-LM (Gemma 4 E2B by default). The model, about 2.6 GB, is downloaded once into Application Support (excluded from iCloud backup). Progress arrives as `nativeDownloadProgress`. Needs an iPhone 13 Pro or newer (6 GB RAM). |
|
|
53
|
+
| `"foundation-models"` | Apple's system model: no download, iOS 26+ on Apple Intelligence devices, about 4,000 tokens of context shared by the system prompt, history and reply. |
|
|
54
|
+
|
|
55
|
+
`auto` never starts the large download on its own just because Foundation Models happens to be
|
|
56
|
+
available. To use the downloadable model on such a device, pass `engine: "litert"`:
|
|
57
|
+
|
|
58
|
+
```js
|
|
59
|
+
const ai = useAI({ provider: "litert", model: "gemma-4-E2B" }) // pin LiteRT-LM
|
|
60
|
+
const ai = useAI({ provider: "foundation-models" }) // pin Apple Foundation Models
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The provider names `native` (auto), `litert` and `foundation-models` can also be set app-wide in the AI
|
|
64
|
+
config, so components don't have to choose:
|
|
65
|
+
|
|
66
|
+
```json
|
|
67
|
+
"AI_CONFIG": { "browser": { "provider": "foundation-models" } }
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
(`"provider": "native"` with `"engine": "litert"` is equivalent to `"provider": "litert"`.)
|
|
71
|
+
|
|
72
|
+
`model` and `modelPath` work on both platforms. The `ON_AI_READY` payload includes `engine` so the UI
|
|
73
|
+
can show which one is active.
|
|
@@ -46,7 +46,7 @@ class NativeBridgeAI(
|
|
|
46
46
|
"gemma-4-E2B" to ModelEntry(
|
|
47
47
|
url = "https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it.litertlm",
|
|
48
48
|
filename = "gemma-4-E2B-it.litertlm",
|
|
49
|
-
sizeHint =
|
|
49
|
+
sizeHint = 2_588_147_712L
|
|
50
50
|
),
|
|
51
51
|
"qwen3-0.6B" to ModelEntry(
|
|
52
52
|
url = "https://huggingface.co/litert-community/Qwen3-0.6B-it-litert-lm/resolve/main/Qwen3-0.6B-it-int4.litertlm",
|
|
@@ -125,7 +125,9 @@ class NativeBridgeAI(
|
|
|
125
125
|
private fun buildSystemPrompt(options: JSONObject) {
|
|
126
126
|
val attachmentComponents = options.optJSONObject("attachmentComponents")
|
|
127
127
|
if (attachmentComponents == null || attachmentComponents.length() == 0) {
|
|
128
|
-
|
|
128
|
+
// No components to describe, but the app's own systemPrompt must still reach the model.
|
|
129
|
+
systemPrompt = options.optString("systemPrompt", "").trim()
|
|
130
|
+
log("[attachments] No attachmentComponents provided — using the app systemPrompt only (${systemPrompt.length} chars)")
|
|
129
131
|
return
|
|
130
132
|
}
|
|
131
133
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "catalyst-ai",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "1.0.1-canary.2",
|
|
4
4
|
"description": "AI provider for catalyst-core — cloud/web/native useAI hooks + OpenAI/Gemini SSE route",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -12,10 +12,18 @@
|
|
|
12
12
|
"scripts",
|
|
13
13
|
"android/src",
|
|
14
14
|
"android/build.gradle.kts",
|
|
15
|
+
"plugins",
|
|
16
|
+
"!plugins/ai/Package.swift",
|
|
17
|
+
"!plugins/ai/Tests",
|
|
18
|
+
"!plugins/ai/.build",
|
|
19
|
+
"!plugins/**/.build",
|
|
15
20
|
"README.md"
|
|
16
21
|
],
|
|
17
22
|
"scripts": {
|
|
18
|
-
"preinstall": "node ./scripts/check-peer.js"
|
|
23
|
+
"preinstall": "node ./scripts/check-peer.js",
|
|
24
|
+
"test": "npm run test:types && vitest run",
|
|
25
|
+
"test:watch": "vitest",
|
|
26
|
+
"test:types": "tsc --noEmit"
|
|
19
27
|
},
|
|
20
28
|
"peerDependencies": {
|
|
21
29
|
"catalyst-core": ">=0.3.0-0"
|
|
@@ -30,5 +38,11 @@
|
|
|
30
38
|
"type": "git",
|
|
31
39
|
"url": "https://github.com/tata1mg/catalyst-core.git",
|
|
32
40
|
"directory": "packages/catalyst-ai"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/node": "^22.20.1",
|
|
44
|
+
"@vitest/coverage-v8": "4.1.11",
|
|
45
|
+
"typescript": "^7.0.2",
|
|
46
|
+
"vitest": "4.1.11"
|
|
33
47
|
}
|
|
34
48
|
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// swift-tools-version: 5.9
|
|
2
|
+
// Vendored from google-ai-edge/LiteRT-LM (Apache-2.0), tag v0.17.1 — see VENDORED.md.
|
|
3
|
+
// Upstream's repo tracks large Android/Linux/Windows libraries in Git LFS, which makes
|
|
4
|
+
// `swift package resolve` require git-lfs and clone ~2.7 GB. Vendoring only the Swift wrapper and
|
|
5
|
+
// pointing at the release's prebuilt xcframework avoids both; SwiftPM downloads just that ~120 MB zip.
|
|
6
|
+
import PackageDescription
|
|
7
|
+
|
|
8
|
+
let package = Package(
|
|
9
|
+
name: "LiteRTLM",
|
|
10
|
+
platforms: [
|
|
11
|
+
.iOS(.v15)
|
|
12
|
+
],
|
|
13
|
+
products: [
|
|
14
|
+
.library(name: "LiteRTLM", targets: ["LiteRTLM"])
|
|
15
|
+
],
|
|
16
|
+
targets: [
|
|
17
|
+
.binaryTarget(
|
|
18
|
+
name: "CLiteRTLM",
|
|
19
|
+
url: "https://github.com/google-ai-edge/LiteRT-LM/releases/download/v0.17.1/CLiteRTLM.xcframework.zip",
|
|
20
|
+
checksum: "c94fc12aa0403cb47208e419cc3bfe258214ea17035f7a63c16de536869f2186"
|
|
21
|
+
),
|
|
22
|
+
.target(
|
|
23
|
+
name: "LiteRTLM",
|
|
24
|
+
dependencies: ["CLiteRTLM"],
|
|
25
|
+
path: "Sources/LiteRTLM"
|
|
26
|
+
),
|
|
27
|
+
]
|
|
28
|
+
)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Copyright 2026 Google LLC
|
|
2
|
+
//
|
|
3
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
// you may not use this file except in compliance with the License.
|
|
5
|
+
// You may obtain a copy of the License at
|
|
6
|
+
//
|
|
7
|
+
// https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
//
|
|
9
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
// See the License for the specific language governing permissions and
|
|
13
|
+
// limitations under the License.
|
|
14
|
+
|
|
15
|
+
import Foundation
|
|
16
|
+
import OSLog
|
|
17
|
+
import CLiteRTLM
|
|
18
|
+
|
|
19
|
+
/// Data struct to hold benchmark information. Note that this is an experimental API and may change
|
|
20
|
+
/// in the future.
|
|
21
|
+
public struct BenchmarkInfo {
|
|
22
|
+
/// The time in seconds to initialize the engine and the conversation.
|
|
23
|
+
public let initTimeInSecond: Double
|
|
24
|
+
|
|
25
|
+
/// The time in seconds to the first token.
|
|
26
|
+
public let timeToFirstTokenInSecond: Double
|
|
27
|
+
|
|
28
|
+
/// The number of tokens in the last prefill turn.
|
|
29
|
+
public let lastPrefillTokenCount: Int
|
|
30
|
+
|
|
31
|
+
/// The number of tokens in the last decode turn.
|
|
32
|
+
public let lastDecodeTokenCount: Int
|
|
33
|
+
|
|
34
|
+
/// The number of tokens processed per second in the last prefill.
|
|
35
|
+
public let lastPrefillTokensPerSecond: Double
|
|
36
|
+
|
|
37
|
+
/// The number of tokens processed per second in the last decode.
|
|
38
|
+
public let lastDecodeTokensPerSecond: Double
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// Runs a benchmark on the LiteRT-LM engine.
|
|
42
|
+
///
|
|
43
|
+
/// **Note:** This function can take a significant amount of time depending on the model size,
|
|
44
|
+
/// device hardware, and the number of prefill and decode tokens. It is strongly recommended to
|
|
45
|
+
/// call this method on a background thread to avoid blocking the main thread.
|
|
46
|
+
///
|
|
47
|
+
/// - Parameters:
|
|
48
|
+
/// - modelPath: The path to the model file.
|
|
49
|
+
/// - backend: The backend to use for the engine.
|
|
50
|
+
/// - prefillTokens: The number of tokens to prefill.
|
|
51
|
+
/// - decodeTokens: The number of tokens to decode.
|
|
52
|
+
/// - cacheDir: The directory for placing cache files. Set to ":nocache" to disable caching.
|
|
53
|
+
/// - prompt: The custom prompt string to tokenize and run. If the tokenized prompt is shorter
|
|
54
|
+
/// than `prefillTokens`, the remaining tokens are padded with zero. If it is longer, the
|
|
55
|
+
/// prompt is truncated to `prefillTokens`.
|
|
56
|
+
/// - Returns: The benchmark info.
|
|
57
|
+
/// - Throws: A `LiteRTLMError` if the engine fails to initialize or generate benchmark info.
|
|
58
|
+
public func benchmark(
|
|
59
|
+
modelPath: String,
|
|
60
|
+
backend: Backend,
|
|
61
|
+
visionBackend: Backend? = nil,
|
|
62
|
+
audioBackend: Backend? = nil,
|
|
63
|
+
prefillTokens: Int = 256,
|
|
64
|
+
decodeTokens: Int = 256,
|
|
65
|
+
cacheDir: String? = nil,
|
|
66
|
+
prompt: String = "How are you"
|
|
67
|
+
) async throws -> BenchmarkInfo {
|
|
68
|
+
ExperimentalFlags.optIntoExperimentalAPIs()
|
|
69
|
+
|
|
70
|
+
// temporarily enable benchmark flag so that Conversation API correctly passes checks later
|
|
71
|
+
let previousBenchmarkFlag = ExperimentalFlags.enableBenchmark
|
|
72
|
+
ExperimentalFlags.enableBenchmark = true
|
|
73
|
+
defer {
|
|
74
|
+
ExperimentalFlags.enableBenchmark = previousBenchmarkFlag
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let engineConfig = try EngineConfig(
|
|
78
|
+
modelPath: modelPath,
|
|
79
|
+
backend: backend,
|
|
80
|
+
visionBackend: visionBackend,
|
|
81
|
+
audioBackend: audioBackend,
|
|
82
|
+
maxNumTokens: prefillTokens + decodeTokens + 32,
|
|
83
|
+
cacheDir: cacheDir
|
|
84
|
+
)
|
|
85
|
+
let engine = Engine(engineConfig: engineConfig)
|
|
86
|
+
try await engine.initializeForBenchmark(prefillTokens: prefillTokens, decodeTokens: decodeTokens)
|
|
87
|
+
|
|
88
|
+
let conversation = try await engine.createConversation()
|
|
89
|
+
_ = try await conversation.sendMessage(Message(prompt))
|
|
90
|
+
return try conversation.getBenchmarkInfo()
|
|
91
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Copyright 2026 Google LLC
|
|
2
|
+
//
|
|
3
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
// you may not use this file except in compliance with the License.
|
|
5
|
+
// You may obtain a copy of the License at
|
|
6
|
+
//
|
|
7
|
+
// https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
//
|
|
9
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
// See the License for the specific language governing permissions and
|
|
13
|
+
// limitations under the License.
|
|
14
|
+
|
|
15
|
+
import Foundation
|
|
16
|
+
import CLiteRTLM
|
|
17
|
+
|
|
18
|
+
/// Supported input/output modalities.
|
|
19
|
+
public struct SupportedModalities: Equatable {
|
|
20
|
+
public let text: Bool
|
|
21
|
+
public let vision: Bool
|
|
22
|
+
public let audio: Bool
|
|
23
|
+
public let video: Bool
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// Default sampler parameters.
|
|
27
|
+
/// TODO: b/554164915 - Reuse SamplerConfig instead of SamplerParameters (matching Python),
|
|
28
|
+
/// once SamplerConfig can support optional fields to represent unset/0 values from models.
|
|
29
|
+
public struct SamplerParameters: Equatable {
|
|
30
|
+
public let type: LiteRtLmSamplerType
|
|
31
|
+
public let temperature: Float
|
|
32
|
+
public let topK: Int
|
|
33
|
+
public let topP: Float
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// Provides information about capabilities and features supported by a LiteRT-LM file.
|
|
37
|
+
///
|
|
38
|
+
/// ### Example Usage:
|
|
39
|
+
/// ```swift
|
|
40
|
+
/// // 1. Load the model metadata
|
|
41
|
+
/// guard let capabilities = Capabilities(modelPath: "/path/to/model.litertlm") else {
|
|
42
|
+
/// print("Failed to load model file capabilities.")
|
|
43
|
+
/// return
|
|
44
|
+
/// }
|
|
45
|
+
/// // 2. Query basic capability flags
|
|
46
|
+
/// let supportsThinking = capabilities.supportsThinking()
|
|
47
|
+
/// let supportsFunctionCall = capabilities.supportsFunctionCalling()
|
|
48
|
+
/// let hasSpeculativeDecoding = capabilities.hasSpeculativeDecodingSupport()
|
|
49
|
+
///
|
|
50
|
+
/// // 3. Check supported input modalities
|
|
51
|
+
/// if capabilities.inputModalities.vision {
|
|
52
|
+
/// print("Vision input is supported!")
|
|
53
|
+
/// }
|
|
54
|
+
///
|
|
55
|
+
/// // 4. Check vision token budget
|
|
56
|
+
/// let visionBudget = capabilities.maxVisionTokenBudget()
|
|
57
|
+
/// ```
|
|
58
|
+
public class Capabilities {
|
|
59
|
+
private let handle: OpaquePointer
|
|
60
|
+
|
|
61
|
+
/// Loads a LiteRT-LM file from the given path.
|
|
62
|
+
/// Returns nil if the file cannot be opened.
|
|
63
|
+
public init?(modelPath: String) {
|
|
64
|
+
guard let handle = litert_lm_loaded_file_create(modelPath) else {
|
|
65
|
+
return nil
|
|
66
|
+
}
|
|
67
|
+
self.handle = handle
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// Checks if the loaded LiteRT-LM file supports speculative decoding.
|
|
71
|
+
public func hasSpeculativeDecodingSupport() -> Bool {
|
|
72
|
+
return litert_lm_loaded_file_has_speculative_decoding_support(handle)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/// Checks if the loaded LiteRT-LM file supports thinking/reasoning.
|
|
76
|
+
public func supportsThinking() -> Bool {
|
|
77
|
+
return litert_lm_loaded_file_supports_thinking(handle)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/// Checks if the loaded LiteRT-LM file supports function calling/tool use.
|
|
81
|
+
public func supportsFunctionCalling() -> Bool {
|
|
82
|
+
return litert_lm_loaded_file_supports_function_calling(handle)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/// Returns the supported input modalities.
|
|
86
|
+
public var inputModalities: SupportedModalities {
|
|
87
|
+
return SupportedModalities(
|
|
88
|
+
text: litert_lm_loaded_file_supports_input_modality(handle, kLiteRtLmModalityText),
|
|
89
|
+
vision: litert_lm_loaded_file_supports_input_modality(handle, kLiteRtLmModalityVision),
|
|
90
|
+
audio: litert_lm_loaded_file_supports_input_modality(handle, kLiteRtLmModalityAudio),
|
|
91
|
+
video: litert_lm_loaded_file_supports_input_modality(handle, kLiteRtLmModalityVideo)
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Returns the default sampler parameters for the model.
|
|
96
|
+
public var defaultSamplerParams: SamplerParameters {
|
|
97
|
+
return SamplerParameters(
|
|
98
|
+
type: litert_lm_loaded_file_sampler_type(handle),
|
|
99
|
+
temperature: litert_lm_loaded_file_sampler_temperature(handle),
|
|
100
|
+
topK: Int(litert_lm_loaded_file_sampler_top_k(handle)),
|
|
101
|
+
topP: litert_lm_loaded_file_sampler_top_p(handle)
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/// Returns the maximum vision token budget for the model.
|
|
106
|
+
/// Returns -1 if the model does not support vision or if the budget is not defined.
|
|
107
|
+
public func maxVisionTokenBudget() -> Int {
|
|
108
|
+
return Int(litert_lm_loaded_file_max_vision_token_budget(handle))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
deinit {
|
|
112
|
+
litert_lm_loaded_file_delete(handle)
|
|
113
|
+
}
|
|
114
|
+
}
|