@firebase/ai 2.1.0-canary.c5f08a9bc → 2.1.0-canary.cbef6c6e5
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/dist/ai-public.d.ts +115 -1
- package/dist/ai.d.ts +153 -1
- package/dist/esm/index.esm.js +370 -360
- package/dist/esm/index.esm.js.map +1 -1
- package/dist/esm/src/index.d.ts +2 -1
- package/dist/esm/src/methods/chrome-adapter.d.ts +7 -3
- package/dist/esm/src/service.d.ts +4 -2
- package/dist/index.cjs.js +370 -360
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.node.cjs.js +8 -293
- package/dist/index.node.cjs.js.map +1 -1
- package/dist/index.node.mjs +8 -293
- package/dist/index.node.mjs.map +1 -1
- package/dist/src/index.d.ts +2 -1
- package/dist/src/methods/chrome-adapter.d.ts +7 -3
- package/dist/src/service.d.ts +4 -2
- package/package.json +10 -8
package/dist/index.node.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { FirebaseError, getModularInstance } from '@firebase/util';
|
|
|
4
4
|
import { Logger } from '@firebase/logger';
|
|
5
5
|
|
|
6
6
|
var name = "@firebase/ai";
|
|
7
|
-
var version = "2.1.0-canary.
|
|
7
|
+
var version = "2.1.0-canary.cbef6c6e5";
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* @license
|
|
@@ -636,9 +636,10 @@ class VertexAIBackend extends Backend {
|
|
|
636
636
|
* limitations under the License.
|
|
637
637
|
*/
|
|
638
638
|
class AIService {
|
|
639
|
-
constructor(app, backend, authProvider, appCheckProvider) {
|
|
639
|
+
constructor(app, backend, authProvider, appCheckProvider, chromeAdapterFactory) {
|
|
640
640
|
this.app = app;
|
|
641
641
|
this.backend = backend;
|
|
642
|
+
this.chromeAdapterFactory = chromeAdapterFactory;
|
|
642
643
|
const appCheck = appCheckProvider?.getImmediate({ optional: true });
|
|
643
644
|
const auth = authProvider?.getImmediate({ optional: true });
|
|
644
645
|
this.auth = auth || null;
|
|
@@ -2347,292 +2348,6 @@ class ImagenModel extends AIModel {
|
|
|
2347
2348
|
}
|
|
2348
2349
|
}
|
|
2349
2350
|
|
|
2350
|
-
/**
|
|
2351
|
-
* @internal
|
|
2352
|
-
*/
|
|
2353
|
-
var Availability;
|
|
2354
|
-
(function (Availability) {
|
|
2355
|
-
Availability["UNAVAILABLE"] = "unavailable";
|
|
2356
|
-
Availability["DOWNLOADABLE"] = "downloadable";
|
|
2357
|
-
Availability["DOWNLOADING"] = "downloading";
|
|
2358
|
-
Availability["AVAILABLE"] = "available";
|
|
2359
|
-
})(Availability || (Availability = {}));
|
|
2360
|
-
|
|
2361
|
-
/**
|
|
2362
|
-
* @license
|
|
2363
|
-
* Copyright 2025 Google LLC
|
|
2364
|
-
*
|
|
2365
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2366
|
-
* you may not use this file except in compliance with the License.
|
|
2367
|
-
* You may obtain a copy of the License at
|
|
2368
|
-
*
|
|
2369
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2370
|
-
*
|
|
2371
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
2372
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2373
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2374
|
-
* See the License for the specific language governing permissions and
|
|
2375
|
-
* limitations under the License.
|
|
2376
|
-
*/
|
|
2377
|
-
/**
|
|
2378
|
-
* Defines an inference "backend" that uses Chrome's on-device model,
|
|
2379
|
-
* and encapsulates logic for detecting when on-device inference is
|
|
2380
|
-
* possible.
|
|
2381
|
-
*/
|
|
2382
|
-
class ChromeAdapterImpl {
|
|
2383
|
-
constructor(languageModelProvider, mode, onDeviceParams = {
|
|
2384
|
-
createOptions: {
|
|
2385
|
-
// Defaults to support image inputs for convenience.
|
|
2386
|
-
expectedInputs: [{ type: 'image' }]
|
|
2387
|
-
}
|
|
2388
|
-
}) {
|
|
2389
|
-
this.languageModelProvider = languageModelProvider;
|
|
2390
|
-
this.mode = mode;
|
|
2391
|
-
this.onDeviceParams = onDeviceParams;
|
|
2392
|
-
this.isDownloading = false;
|
|
2393
|
-
}
|
|
2394
|
-
/**
|
|
2395
|
-
* Checks if a given request can be made on-device.
|
|
2396
|
-
*
|
|
2397
|
-
* Encapsulates a few concerns:
|
|
2398
|
-
* the mode
|
|
2399
|
-
* API existence
|
|
2400
|
-
* prompt formatting
|
|
2401
|
-
* model availability, including triggering download if necessary
|
|
2402
|
-
*
|
|
2403
|
-
*
|
|
2404
|
-
* Pros: callers needn't be concerned with details of on-device availability.</p>
|
|
2405
|
-
* Cons: this method spans a few concerns and splits request validation from usage.
|
|
2406
|
-
* If instance variables weren't already part of the API, we could consider a better
|
|
2407
|
-
* separation of concerns.
|
|
2408
|
-
*/
|
|
2409
|
-
async isAvailable(request) {
|
|
2410
|
-
if (!this.mode) {
|
|
2411
|
-
logger.debug(`On-device inference unavailable because mode is undefined.`);
|
|
2412
|
-
return false;
|
|
2413
|
-
}
|
|
2414
|
-
if (this.mode === InferenceMode.ONLY_IN_CLOUD) {
|
|
2415
|
-
logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
|
|
2416
|
-
return false;
|
|
2417
|
-
}
|
|
2418
|
-
// Triggers out-of-band download so model will eventually become available.
|
|
2419
|
-
const availability = await this.downloadIfAvailable();
|
|
2420
|
-
if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
|
|
2421
|
-
// If it will never be available due to API inavailability, throw.
|
|
2422
|
-
if (availability === Availability.UNAVAILABLE) {
|
|
2423
|
-
throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
|
|
2424
|
-
}
|
|
2425
|
-
else if (availability === Availability.DOWNLOADABLE ||
|
|
2426
|
-
availability === Availability.DOWNLOADING) {
|
|
2427
|
-
// TODO(chholland): Better user experience during download - progress?
|
|
2428
|
-
logger.debug(`Waiting for download of LanguageModel to complete.`);
|
|
2429
|
-
await this.downloadPromise;
|
|
2430
|
-
return true;
|
|
2431
|
-
}
|
|
2432
|
-
return true;
|
|
2433
|
-
}
|
|
2434
|
-
// Applies prefer_on_device logic.
|
|
2435
|
-
if (availability !== Availability.AVAILABLE) {
|
|
2436
|
-
logger.debug(`On-device inference unavailable because availability is "${availability}".`);
|
|
2437
|
-
return false;
|
|
2438
|
-
}
|
|
2439
|
-
if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
|
|
2440
|
-
logger.debug(`On-device inference unavailable because request is incompatible.`);
|
|
2441
|
-
return false;
|
|
2442
|
-
}
|
|
2443
|
-
return true;
|
|
2444
|
-
}
|
|
2445
|
-
/**
|
|
2446
|
-
* Generates content on device.
|
|
2447
|
-
*
|
|
2448
|
-
* @remarks
|
|
2449
|
-
* This is comparable to {@link GenerativeModel.generateContent} for generating content in
|
|
2450
|
-
* Cloud.
|
|
2451
|
-
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
2452
|
-
* @returns {@link Response}, so we can reuse common response formatting.
|
|
2453
|
-
*/
|
|
2454
|
-
async generateContent(request) {
|
|
2455
|
-
const session = await this.createSession();
|
|
2456
|
-
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
2457
|
-
const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
|
|
2458
|
-
return ChromeAdapterImpl.toResponse(text);
|
|
2459
|
-
}
|
|
2460
|
-
/**
|
|
2461
|
-
* Generates content stream on device.
|
|
2462
|
-
*
|
|
2463
|
-
* @remarks
|
|
2464
|
-
* This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
|
|
2465
|
-
* Cloud.
|
|
2466
|
-
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
2467
|
-
* @returns {@link Response}, so we can reuse common response formatting.
|
|
2468
|
-
*/
|
|
2469
|
-
async generateContentStream(request) {
|
|
2470
|
-
const session = await this.createSession();
|
|
2471
|
-
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
2472
|
-
const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
|
|
2473
|
-
return ChromeAdapterImpl.toStreamResponse(stream);
|
|
2474
|
-
}
|
|
2475
|
-
async countTokens(_request) {
|
|
2476
|
-
throw new AIError(AIErrorCode.REQUEST_ERROR, 'Count Tokens is not yet available for on-device model.');
|
|
2477
|
-
}
|
|
2478
|
-
/**
|
|
2479
|
-
* Asserts inference for the given request can be performed by an on-device model.
|
|
2480
|
-
*/
|
|
2481
|
-
static isOnDeviceRequest(request) {
|
|
2482
|
-
// Returns false if the prompt is empty.
|
|
2483
|
-
if (request.contents.length === 0) {
|
|
2484
|
-
logger.debug('Empty prompt rejected for on-device inference.');
|
|
2485
|
-
return false;
|
|
2486
|
-
}
|
|
2487
|
-
for (const content of request.contents) {
|
|
2488
|
-
if (content.role === 'function') {
|
|
2489
|
-
logger.debug(`"Function" role rejected for on-device inference.`);
|
|
2490
|
-
return false;
|
|
2491
|
-
}
|
|
2492
|
-
// Returns false if request contains an image with an unsupported mime type.
|
|
2493
|
-
for (const part of content.parts) {
|
|
2494
|
-
if (part.inlineData &&
|
|
2495
|
-
ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
|
|
2496
|
-
logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
|
|
2497
|
-
return false;
|
|
2498
|
-
}
|
|
2499
|
-
}
|
|
2500
|
-
}
|
|
2501
|
-
return true;
|
|
2502
|
-
}
|
|
2503
|
-
/**
|
|
2504
|
-
* Encapsulates logic to get availability and download a model if one is downloadable.
|
|
2505
|
-
*/
|
|
2506
|
-
async downloadIfAvailable() {
|
|
2507
|
-
const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
|
|
2508
|
-
if (availability === Availability.DOWNLOADABLE) {
|
|
2509
|
-
this.download();
|
|
2510
|
-
}
|
|
2511
|
-
return availability;
|
|
2512
|
-
}
|
|
2513
|
-
/**
|
|
2514
|
-
* Triggers out-of-band download of an on-device model.
|
|
2515
|
-
*
|
|
2516
|
-
* Chrome only downloads models as needed. Chrome knows a model is needed when code calls
|
|
2517
|
-
* LanguageModel.create.
|
|
2518
|
-
*
|
|
2519
|
-
* Since Chrome manages the download, the SDK can only avoid redundant download requests by
|
|
2520
|
-
* tracking if a download has previously been requested.
|
|
2521
|
-
*/
|
|
2522
|
-
download() {
|
|
2523
|
-
if (this.isDownloading) {
|
|
2524
|
-
return;
|
|
2525
|
-
}
|
|
2526
|
-
this.isDownloading = true;
|
|
2527
|
-
this.downloadPromise = this.languageModelProvider
|
|
2528
|
-
?.create(this.onDeviceParams.createOptions)
|
|
2529
|
-
.finally(() => {
|
|
2530
|
-
this.isDownloading = false;
|
|
2531
|
-
});
|
|
2532
|
-
}
|
|
2533
|
-
/**
|
|
2534
|
-
* Converts Firebase AI {@link Content} object to a Chrome {@link LanguageModelMessage} object.
|
|
2535
|
-
*/
|
|
2536
|
-
static async toLanguageModelMessage(content) {
|
|
2537
|
-
const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
|
|
2538
|
-
return {
|
|
2539
|
-
role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
|
|
2540
|
-
content: languageModelMessageContents
|
|
2541
|
-
};
|
|
2542
|
-
}
|
|
2543
|
-
/**
|
|
2544
|
-
* Converts a Firebase AI Part object to a Chrome LanguageModelMessageContent object.
|
|
2545
|
-
*/
|
|
2546
|
-
static async toLanguageModelMessageContent(part) {
|
|
2547
|
-
if (part.text) {
|
|
2548
|
-
return {
|
|
2549
|
-
type: 'text',
|
|
2550
|
-
value: part.text
|
|
2551
|
-
};
|
|
2552
|
-
}
|
|
2553
|
-
else if (part.inlineData) {
|
|
2554
|
-
const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
|
|
2555
|
-
const imageBlob = await formattedImageContent.blob();
|
|
2556
|
-
const imageBitmap = await createImageBitmap(imageBlob);
|
|
2557
|
-
return {
|
|
2558
|
-
type: 'image',
|
|
2559
|
-
value: imageBitmap
|
|
2560
|
-
};
|
|
2561
|
-
}
|
|
2562
|
-
throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
|
|
2563
|
-
}
|
|
2564
|
-
/**
|
|
2565
|
-
* Converts a Firebase AI {@link Role} string to a {@link LanguageModelMessageRole} string.
|
|
2566
|
-
*/
|
|
2567
|
-
static toLanguageModelMessageRole(role) {
|
|
2568
|
-
// Assumes 'function' rule has been filtered by isOnDeviceRequest
|
|
2569
|
-
return role === 'model' ? 'assistant' : 'user';
|
|
2570
|
-
}
|
|
2571
|
-
/**
|
|
2572
|
-
* Abstracts Chrome session creation.
|
|
2573
|
-
*
|
|
2574
|
-
* Chrome uses a multi-turn session for all inference. Firebase AI uses single-turn for all
|
|
2575
|
-
* inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
|
|
2576
|
-
* inference.
|
|
2577
|
-
*
|
|
2578
|
-
* Chrome will remove a model from memory if it's no longer in use, so this method ensures a
|
|
2579
|
-
* new session is created before an old session is destroyed.
|
|
2580
|
-
*/
|
|
2581
|
-
async createSession() {
|
|
2582
|
-
if (!this.languageModelProvider) {
|
|
2583
|
-
throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
|
|
2584
|
-
}
|
|
2585
|
-
const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
|
|
2586
|
-
if (this.oldSession) {
|
|
2587
|
-
this.oldSession.destroy();
|
|
2588
|
-
}
|
|
2589
|
-
// Holds session reference, so model isn't unloaded from memory.
|
|
2590
|
-
this.oldSession = newSession;
|
|
2591
|
-
return newSession;
|
|
2592
|
-
}
|
|
2593
|
-
/**
|
|
2594
|
-
* Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
|
|
2595
|
-
*/
|
|
2596
|
-
static toResponse(text) {
|
|
2597
|
-
return {
|
|
2598
|
-
json: async () => ({
|
|
2599
|
-
candidates: [
|
|
2600
|
-
{
|
|
2601
|
-
content: {
|
|
2602
|
-
parts: [{ text }]
|
|
2603
|
-
}
|
|
2604
|
-
}
|
|
2605
|
-
]
|
|
2606
|
-
})
|
|
2607
|
-
};
|
|
2608
|
-
}
|
|
2609
|
-
/**
|
|
2610
|
-
* Formats string stream returned by Chrome as SSE returned by Firebase AI.
|
|
2611
|
-
*/
|
|
2612
|
-
static toStreamResponse(stream) {
|
|
2613
|
-
const encoder = new TextEncoder();
|
|
2614
|
-
return {
|
|
2615
|
-
body: stream.pipeThrough(new TransformStream({
|
|
2616
|
-
transform(chunk, controller) {
|
|
2617
|
-
const json = JSON.stringify({
|
|
2618
|
-
candidates: [
|
|
2619
|
-
{
|
|
2620
|
-
content: {
|
|
2621
|
-
role: 'model',
|
|
2622
|
-
parts: [{ text: chunk }]
|
|
2623
|
-
}
|
|
2624
|
-
}
|
|
2625
|
-
]
|
|
2626
|
-
});
|
|
2627
|
-
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
|
2628
|
-
}
|
|
2629
|
-
}))
|
|
2630
|
-
};
|
|
2631
|
-
}
|
|
2632
|
-
}
|
|
2633
|
-
// Visible for testing
|
|
2634
|
-
ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
|
|
2635
|
-
|
|
2636
2351
|
/**
|
|
2637
2352
|
* @license
|
|
2638
2353
|
* Copyright 2024 Google LLC
|
|
@@ -3020,11 +2735,11 @@ function getGenerativeModel(ai, modelParams, requestOptions) {
|
|
|
3020
2735
|
if (!inCloudParams.model) {
|
|
3021
2736
|
throw new AIError(AIErrorCode.NO_MODEL, `Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })`);
|
|
3022
2737
|
}
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
2738
|
+
/**
|
|
2739
|
+
* An AIService registered by index.node.ts will not have a
|
|
2740
|
+
* chromeAdapterFactory() method.
|
|
2741
|
+
*/
|
|
2742
|
+
const chromeAdapter = ai.chromeAdapterFactory?.(hybridParams.mode, typeof window === 'undefined' ? undefined : window, hybridParams.onDeviceParams);
|
|
3028
2743
|
return new GenerativeModel(ai, inCloudParams, requestOptions, chromeAdapter);
|
|
3029
2744
|
}
|
|
3030
2745
|
/**
|