@browser-ai/core 1.0.0

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.
@@ -0,0 +1,243 @@
1
+ import { LanguageModelV2, LanguageModelV2CallOptions, LanguageModelV2Content, LanguageModelV2FinishReason, LanguageModelV2CallWarning, LanguageModelV2StreamPart, EmbeddingModelV2, EmbeddingModelV2Embedding, ProviderV2 } from '@ai-sdk/provider';
2
+ import { TextEmbedder } from '@mediapipe/tasks-text';
3
+ import { UIMessage } from 'ai';
4
+
5
+ type BuiltInAIChatModelId = "text";
6
+ interface BuiltInAIChatSettings extends LanguageModelCreateOptions {
7
+ /**
8
+ * Expected input types for the session, for multimodal inputs.
9
+ */
10
+ expectedInputs?: Array<{
11
+ type: "text" | "image" | "audio";
12
+ languages?: string[];
13
+ }>;
14
+ }
15
+ /**
16
+ * Check if the browser supports the built-in AI API
17
+ * @returns true if the browser supports the built-in AI API, false otherwise
18
+ */
19
+ declare function doesBrowserSupportBuiltInAI(): boolean;
20
+ /**
21
+ * Check if the Prompt API is available
22
+ * @deprecated Use `doesBrowserSupportBuiltInAI()` instead for clearer naming
23
+ * @returns true if the browser supports the built-in AI API, false otherwise
24
+ */
25
+ declare function isBuiltInAIModelAvailable(): boolean;
26
+ declare class BuiltInAIChatLanguageModel implements LanguageModelV2 {
27
+ readonly specificationVersion = "v2";
28
+ readonly modelId: BuiltInAIChatModelId;
29
+ readonly provider = "browser-ai";
30
+ private readonly config;
31
+ private readonly sessionManager;
32
+ constructor(modelId: BuiltInAIChatModelId, options?: BuiltInAIChatSettings);
33
+ readonly supportedUrls: Record<string, RegExp[]>;
34
+ /**
35
+ * Gets a session with the specified options
36
+ * Delegates to SessionManager for all session lifecycle management
37
+ * @private
38
+ */
39
+ private getSession;
40
+ private getArgs;
41
+ /**
42
+ * Generates a complete text response using the browser's built-in Prompt API
43
+ * @param options
44
+ * @returns Promise resolving to the generated content with finish reason, usage stats, and any warnings
45
+ * @throws {LoadSettingError} When the Prompt API is not available or model needs to be downloaded
46
+ * @throws {UnsupportedFunctionalityError} When unsupported features like file input are used
47
+ */
48
+ doGenerate(options: LanguageModelV2CallOptions): Promise<{
49
+ content: LanguageModelV2Content[];
50
+ finishReason: LanguageModelV2FinishReason;
51
+ usage: {
52
+ inputTokens: undefined;
53
+ outputTokens: undefined;
54
+ totalTokens: undefined;
55
+ };
56
+ request: {
57
+ body: {
58
+ messages: LanguageModelMessage[];
59
+ options: LanguageModelPromptOptions & LanguageModelCreateCoreOptions;
60
+ };
61
+ };
62
+ warnings: LanguageModelV2CallWarning[];
63
+ }>;
64
+ /**
65
+ * Check the availability of the built-in AI model
66
+ * @returns Promise resolving to "unavailable", "available", or "available-after-download"
67
+ */
68
+ availability(): Promise<Availability>;
69
+ /**
70
+ * Creates a session with download progress monitoring.
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * const session = await model.createSessionWithProgress(
75
+ * (progress) => {
76
+ * console.log(`Download progress: ${Math.round(progress * 100)}%`);
77
+ * }
78
+ * );
79
+ * ```
80
+ *
81
+ * @param onDownloadProgress Optional callback receiving progress values 0-1 during model download
82
+ * @returns Promise resolving to a configured LanguageModel session
83
+ * @throws {LoadSettingError} When the Prompt API is not available or model is unavailable
84
+ */
85
+ createSessionWithProgress(onDownloadProgress?: (progress: number) => void): Promise<LanguageModel>;
86
+ /**
87
+ * Generates a streaming text response using the browser's built-in Prompt API
88
+ * @param options
89
+ * @returns Promise resolving to a readable stream of text chunks and request metadata
90
+ * @throws {LoadSettingError} When the Prompt API is not available or model needs to be downloaded
91
+ * @throws {UnsupportedFunctionalityError} When unsupported features like file input are used
92
+ */
93
+ doStream(options: LanguageModelV2CallOptions): Promise<{
94
+ stream: ReadableStream<LanguageModelV2StreamPart>;
95
+ request: {
96
+ body: {
97
+ messages: LanguageModelMessage[];
98
+ options: LanguageModelPromptOptions & LanguageModelCreateCoreOptions;
99
+ };
100
+ };
101
+ }>;
102
+ }
103
+
104
+ interface BuiltInAIEmbeddingModelSettings {
105
+ /**
106
+ * An optional base path to specify the directory the Wasm files should be loaded from.
107
+ * @default 'https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/text_wasm_internal.js'
108
+ */
109
+ wasmLoaderPath?: string;
110
+ /**
111
+ * It's about 6mb before gzip.
112
+ * @default 'https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/text_wasm_internal.wasm'
113
+ */
114
+ wasmBinaryPath?: string;
115
+ /**
116
+ * The model path to the model asset file.
117
+ * It's about 6.1mb before gzip.
118
+ * @default 'https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/universal_sentence_encoder.tflite'
119
+ */
120
+ modelAssetPath?: string;
121
+ /**
122
+ * Whether to normalize the returned feature vector with L2 norm. Use this
123
+ * option only if the model does not already contain a native L2_NORMALIZATION
124
+ * TF Lite Op. In most cases, this is already the case and L2 norm is thus
125
+ * achieved through TF Lite inference.
126
+ * @default false
127
+ */
128
+ l2Normalize?: boolean;
129
+ /**
130
+ * Whether the returned embedding should be quantized to bytes via scalar
131
+ * quantization. Embeddings are implicitly assumed to be unit-norm and
132
+ * therefore any dimension is guaranteed to have a value in [-1.0, 1.0]. Use
133
+ * the l2_normalize option if this is not the case.
134
+ * @default false
135
+ */
136
+ quantize?: boolean;
137
+ /**
138
+ * Overrides the default backend to use for the provided model.
139
+ */
140
+ delegate?: "CPU" | "GPU";
141
+ }
142
+ declare class BuiltInAIEmbeddingModel implements EmbeddingModelV2<string> {
143
+ readonly specificationVersion = "v2";
144
+ readonly provider = "google-mediapipe";
145
+ readonly modelId: string;
146
+ readonly supportsParallelCalls = true;
147
+ readonly maxEmbeddingsPerCall: undefined;
148
+ private settings;
149
+ private modelAssetBuffer;
150
+ private textEmbedder;
151
+ constructor(settings?: BuiltInAIEmbeddingModelSettings);
152
+ protected getTextEmbedder: () => Promise<TextEmbedder>;
153
+ doEmbed: (options: {
154
+ values: string[];
155
+ abortSignal?: AbortSignal;
156
+ }) => Promise<{
157
+ embeddings: Array<EmbeddingModelV2Embedding>;
158
+ rawResponse?: Record<PropertyKey, any>;
159
+ }>;
160
+ }
161
+
162
+ interface BuiltInAIProvider extends ProviderV2 {
163
+ (modelId?: BuiltInAIChatModelId, settings?: BuiltInAIChatSettings): BuiltInAIChatLanguageModel;
164
+ /**
165
+ * Creates a model for text generation.
166
+ */
167
+ languageModel(modelId: BuiltInAIChatModelId, settings?: BuiltInAIChatSettings): BuiltInAIChatLanguageModel;
168
+ /**
169
+ * Creates a model for text generation.
170
+ */
171
+ chat(modelId: BuiltInAIChatModelId, settings?: BuiltInAIChatSettings): BuiltInAIChatLanguageModel;
172
+ textEmbedding(modelId: "embedding", settings?: BuiltInAIEmbeddingModelSettings): EmbeddingModelV2<string>;
173
+ textEmbeddingModel: (modelId: "embedding", settings?: BuiltInAIEmbeddingModelSettings) => EmbeddingModelV2<string>;
174
+ imageModel(modelId: string): never;
175
+ speechModel(modelId: string): never;
176
+ transcriptionModel(modelId: string): never;
177
+ }
178
+ interface BuiltInAIProviderSettings {
179
+ }
180
+ /**
181
+ * Create a BuiltInAI provider instance.
182
+ */
183
+ declare function createBuiltInAI(options?: BuiltInAIProviderSettings): BuiltInAIProvider;
184
+ /**
185
+ * Default BuiltInAI provider instance.
186
+ */
187
+ declare const builtInAI: BuiltInAIProvider;
188
+
189
+ /**
190
+ * UI message type for built-in AI features with custom data parts.
191
+ *
192
+ * Extends base UIMessage to include specific data part schemas
193
+ * for built-in AI functionality such as model download progress tracking
194
+ *
195
+ * @example
196
+ * // Import and use with useChat hook from @ai-sdk/react
197
+ * ```typescript
198
+ * import { useChat } from "@ai-sdk/react";
199
+ * import { BuiltInAIUIMessage } from "@built-in-ai/core";
200
+ *
201
+ * const { messages, sendMessage } = useChat<BuiltInAIUIMessage>({
202
+ * onData: (dataPart) => {
203
+ * if (dataPart.type === 'data-modelDownloadProgress') {
204
+ * console.log(`Download: ${dataPart.data.progress}%`);
205
+ * }
206
+ * if (dataPart.type === 'data-notification') {
207
+ * console.log(`${dataPart.data.level}: ${dataPart.data.message}`);
208
+ * }
209
+ * }
210
+ * });
211
+ * ```
212
+ *
213
+ * @see {@link https://v5.ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat | useChat hook documentation}
214
+ */
215
+ type BuiltInAIUIMessage = UIMessage<
216
+ never, // No custom metadata type
217
+ {
218
+ /**
219
+ * Model download progress data part for tracking browser AI model download status.
220
+ * Used to display download progress bars and status messages to users.
221
+ */
222
+ modelDownloadProgress: {
223
+ /** Current download/initialization status */
224
+ status: "downloading" | "complete" | "error";
225
+ /** Download progress percentage (0-100), undefined for non-downloading states */
226
+ progress?: number;
227
+ /** Human-readable status message to display to users */
228
+ message: string;
229
+ };
230
+ /**
231
+ * User notification data part for displaying temporary messages and alerts.
232
+ * These are typically transient and not persisted in message history.
233
+ */
234
+ notification: {
235
+ /** The notification message text */
236
+ message: string;
237
+ /** Notification severity level for styling and priority */
238
+ level: "info" | "warning" | "error";
239
+ };
240
+ }
241
+ >;
242
+
243
+ export { BuiltInAIChatLanguageModel, type BuiltInAIChatSettings, BuiltInAIEmbeddingModel, type BuiltInAIEmbeddingModelSettings, type BuiltInAIProvider, type BuiltInAIProviderSettings, type BuiltInAIUIMessage, builtInAI, createBuiltInAI, doesBrowserSupportBuiltInAI, isBuiltInAIModelAvailable };