@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.cjs.js
CHANGED
|
@@ -8,7 +8,7 @@ var util = require('@firebase/util');
|
|
|
8
8
|
var logger$1 = require('@firebase/logger');
|
|
9
9
|
|
|
10
10
|
var name = "@firebase/ai";
|
|
11
|
-
var version = "2.1.0-canary.
|
|
11
|
+
var version = "2.1.0-canary.cbef6c6e5";
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* @license
|
|
@@ -640,9 +640,10 @@ class VertexAIBackend extends Backend {
|
|
|
640
640
|
* limitations under the License.
|
|
641
641
|
*/
|
|
642
642
|
class AIService {
|
|
643
|
-
constructor(app, backend, authProvider, appCheckProvider) {
|
|
643
|
+
constructor(app, backend, authProvider, appCheckProvider, chromeAdapterFactory) {
|
|
644
644
|
this.app = app;
|
|
645
645
|
this.backend = backend;
|
|
646
|
+
this.chromeAdapterFactory = chromeAdapterFactory;
|
|
646
647
|
const appCheck = appCheckProvider?.getImmediate({ optional: true });
|
|
647
648
|
const auth = authProvider?.getImmediate({ optional: true });
|
|
648
649
|
this.auth = auth || null;
|
|
@@ -2351,20 +2352,9 @@ class ImagenModel extends AIModel {
|
|
|
2351
2352
|
}
|
|
2352
2353
|
}
|
|
2353
2354
|
|
|
2354
|
-
/**
|
|
2355
|
-
* @internal
|
|
2356
|
-
*/
|
|
2357
|
-
var Availability;
|
|
2358
|
-
(function (Availability) {
|
|
2359
|
-
Availability["UNAVAILABLE"] = "unavailable";
|
|
2360
|
-
Availability["DOWNLOADABLE"] = "downloadable";
|
|
2361
|
-
Availability["DOWNLOADING"] = "downloading";
|
|
2362
|
-
Availability["AVAILABLE"] = "available";
|
|
2363
|
-
})(Availability || (Availability = {}));
|
|
2364
|
-
|
|
2365
2355
|
/**
|
|
2366
2356
|
* @license
|
|
2367
|
-
* Copyright
|
|
2357
|
+
* Copyright 2024 Google LLC
|
|
2368
2358
|
*
|
|
2369
2359
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2370
2360
|
* you may not use this file except in compliance with the License.
|
|
@@ -2379,362 +2369,87 @@ var Availability;
|
|
|
2379
2369
|
* limitations under the License.
|
|
2380
2370
|
*/
|
|
2381
2371
|
/**
|
|
2382
|
-
*
|
|
2383
|
-
*
|
|
2384
|
-
*
|
|
2372
|
+
* Parent class encompassing all Schema types, with static methods that
|
|
2373
|
+
* allow building specific Schema types. This class can be converted with
|
|
2374
|
+
* `JSON.stringify()` into a JSON string accepted by Vertex AI REST endpoints.
|
|
2375
|
+
* (This string conversion is automatically done when calling SDK methods.)
|
|
2376
|
+
* @public
|
|
2385
2377
|
*/
|
|
2386
|
-
class
|
|
2387
|
-
constructor(
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2378
|
+
class Schema {
|
|
2379
|
+
constructor(schemaParams) {
|
|
2380
|
+
// TODO(dlarocque): Enforce this with union types
|
|
2381
|
+
if (!schemaParams.type && !schemaParams.anyOf) {
|
|
2382
|
+
throw new AIError(AIErrorCode.INVALID_SCHEMA, "A schema must have either a 'type' or an 'anyOf' array of sub-schemas.");
|
|
2391
2383
|
}
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2384
|
+
// eslint-disable-next-line guard-for-in
|
|
2385
|
+
for (const paramKey in schemaParams) {
|
|
2386
|
+
this[paramKey] = schemaParams[paramKey];
|
|
2387
|
+
}
|
|
2388
|
+
// Ensure these are explicitly set to avoid TS errors.
|
|
2389
|
+
this.type = schemaParams.type;
|
|
2390
|
+
this.format = schemaParams.hasOwnProperty('format')
|
|
2391
|
+
? schemaParams.format
|
|
2392
|
+
: undefined;
|
|
2393
|
+
this.nullable = schemaParams.hasOwnProperty('nullable')
|
|
2394
|
+
? !!schemaParams.nullable
|
|
2395
|
+
: false;
|
|
2397
2396
|
}
|
|
2398
2397
|
/**
|
|
2399
|
-
*
|
|
2400
|
-
*
|
|
2401
|
-
*
|
|
2402
|
-
* the mode
|
|
2403
|
-
* API existence
|
|
2404
|
-
* prompt formatting
|
|
2405
|
-
* model availability, including triggering download if necessary
|
|
2406
|
-
*
|
|
2407
|
-
*
|
|
2408
|
-
* Pros: callers needn't be concerned with details of on-device availability.</p>
|
|
2409
|
-
* Cons: this method spans a few concerns and splits request validation from usage.
|
|
2410
|
-
* If instance variables weren't already part of the API, we could consider a better
|
|
2411
|
-
* separation of concerns.
|
|
2398
|
+
* Defines how this Schema should be serialized as JSON.
|
|
2399
|
+
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior
|
|
2400
|
+
* @internal
|
|
2412
2401
|
*/
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
// Triggers out-of-band download so model will eventually become available.
|
|
2423
|
-
const availability = await this.downloadIfAvailable();
|
|
2424
|
-
if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
|
|
2425
|
-
// If it will never be available due to API inavailability, throw.
|
|
2426
|
-
if (availability === Availability.UNAVAILABLE) {
|
|
2427
|
-
throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
|
|
2428
|
-
}
|
|
2429
|
-
else if (availability === Availability.DOWNLOADABLE ||
|
|
2430
|
-
availability === Availability.DOWNLOADING) {
|
|
2431
|
-
// TODO(chholland): Better user experience during download - progress?
|
|
2432
|
-
logger.debug(`Waiting for download of LanguageModel to complete.`);
|
|
2433
|
-
await this.downloadPromise;
|
|
2434
|
-
return true;
|
|
2402
|
+
toJSON() {
|
|
2403
|
+
const obj = {
|
|
2404
|
+
type: this.type
|
|
2405
|
+
};
|
|
2406
|
+
for (const prop in this) {
|
|
2407
|
+
if (this.hasOwnProperty(prop) && this[prop] !== undefined) {
|
|
2408
|
+
if (prop !== 'required' || this.type === SchemaType.OBJECT) {
|
|
2409
|
+
obj[prop] = this[prop];
|
|
2410
|
+
}
|
|
2435
2411
|
}
|
|
2436
|
-
return true;
|
|
2437
2412
|
}
|
|
2438
|
-
|
|
2439
|
-
if (availability !== Availability.AVAILABLE) {
|
|
2440
|
-
logger.debug(`On-device inference unavailable because availability is "${availability}".`);
|
|
2441
|
-
return false;
|
|
2442
|
-
}
|
|
2443
|
-
if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
|
|
2444
|
-
logger.debug(`On-device inference unavailable because request is incompatible.`);
|
|
2445
|
-
return false;
|
|
2446
|
-
}
|
|
2447
|
-
return true;
|
|
2413
|
+
return obj;
|
|
2448
2414
|
}
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
*
|
|
2452
|
-
* @remarks
|
|
2453
|
-
* This is comparable to {@link GenerativeModel.generateContent} for generating content in
|
|
2454
|
-
* Cloud.
|
|
2455
|
-
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
2456
|
-
* @returns {@link Response}, so we can reuse common response formatting.
|
|
2457
|
-
*/
|
|
2458
|
-
async generateContent(request) {
|
|
2459
|
-
const session = await this.createSession();
|
|
2460
|
-
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
2461
|
-
const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
|
|
2462
|
-
return ChromeAdapterImpl.toResponse(text);
|
|
2415
|
+
static array(arrayParams) {
|
|
2416
|
+
return new ArraySchema(arrayParams, arrayParams.items);
|
|
2463
2417
|
}
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
*
|
|
2467
|
-
* @remarks
|
|
2468
|
-
* This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
|
|
2469
|
-
* Cloud.
|
|
2470
|
-
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
2471
|
-
* @returns {@link Response}, so we can reuse common response formatting.
|
|
2472
|
-
*/
|
|
2473
|
-
async generateContentStream(request) {
|
|
2474
|
-
const session = await this.createSession();
|
|
2475
|
-
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
2476
|
-
const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
|
|
2477
|
-
return ChromeAdapterImpl.toStreamResponse(stream);
|
|
2418
|
+
static object(objectParams) {
|
|
2419
|
+
return new ObjectSchema(objectParams, objectParams.properties, objectParams.optionalProperties);
|
|
2478
2420
|
}
|
|
2479
|
-
|
|
2480
|
-
|
|
2421
|
+
// eslint-disable-next-line id-blacklist
|
|
2422
|
+
static string(stringParams) {
|
|
2423
|
+
return new StringSchema(stringParams);
|
|
2481
2424
|
}
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
*/
|
|
2485
|
-
static isOnDeviceRequest(request) {
|
|
2486
|
-
// Returns false if the prompt is empty.
|
|
2487
|
-
if (request.contents.length === 0) {
|
|
2488
|
-
logger.debug('Empty prompt rejected for on-device inference.');
|
|
2489
|
-
return false;
|
|
2490
|
-
}
|
|
2491
|
-
for (const content of request.contents) {
|
|
2492
|
-
if (content.role === 'function') {
|
|
2493
|
-
logger.debug(`"Function" role rejected for on-device inference.`);
|
|
2494
|
-
return false;
|
|
2495
|
-
}
|
|
2496
|
-
// Returns false if request contains an image with an unsupported mime type.
|
|
2497
|
-
for (const part of content.parts) {
|
|
2498
|
-
if (part.inlineData &&
|
|
2499
|
-
ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
|
|
2500
|
-
logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
|
|
2501
|
-
return false;
|
|
2502
|
-
}
|
|
2503
|
-
}
|
|
2504
|
-
}
|
|
2505
|
-
return true;
|
|
2425
|
+
static enumString(stringParams) {
|
|
2426
|
+
return new StringSchema(stringParams, stringParams.enum);
|
|
2506
2427
|
}
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
*/
|
|
2510
|
-
async downloadIfAvailable() {
|
|
2511
|
-
const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
|
|
2512
|
-
if (availability === Availability.DOWNLOADABLE) {
|
|
2513
|
-
this.download();
|
|
2514
|
-
}
|
|
2515
|
-
return availability;
|
|
2428
|
+
static integer(integerParams) {
|
|
2429
|
+
return new IntegerSchema(integerParams);
|
|
2516
2430
|
}
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
* Chrome only downloads models as needed. Chrome knows a model is needed when code calls
|
|
2521
|
-
* LanguageModel.create.
|
|
2522
|
-
*
|
|
2523
|
-
* Since Chrome manages the download, the SDK can only avoid redundant download requests by
|
|
2524
|
-
* tracking if a download has previously been requested.
|
|
2525
|
-
*/
|
|
2526
|
-
download() {
|
|
2527
|
-
if (this.isDownloading) {
|
|
2528
|
-
return;
|
|
2529
|
-
}
|
|
2530
|
-
this.isDownloading = true;
|
|
2531
|
-
this.downloadPromise = this.languageModelProvider
|
|
2532
|
-
?.create(this.onDeviceParams.createOptions)
|
|
2533
|
-
.finally(() => {
|
|
2534
|
-
this.isDownloading = false;
|
|
2535
|
-
});
|
|
2431
|
+
// eslint-disable-next-line id-blacklist
|
|
2432
|
+
static number(numberParams) {
|
|
2433
|
+
return new NumberSchema(numberParams);
|
|
2536
2434
|
}
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
static async toLanguageModelMessage(content) {
|
|
2541
|
-
const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
|
|
2542
|
-
return {
|
|
2543
|
-
role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
|
|
2544
|
-
content: languageModelMessageContents
|
|
2545
|
-
};
|
|
2435
|
+
// eslint-disable-next-line id-blacklist
|
|
2436
|
+
static boolean(booleanParams) {
|
|
2437
|
+
return new BooleanSchema(booleanParams);
|
|
2546
2438
|
}
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
*/
|
|
2550
|
-
static async toLanguageModelMessageContent(part) {
|
|
2551
|
-
if (part.text) {
|
|
2552
|
-
return {
|
|
2553
|
-
type: 'text',
|
|
2554
|
-
value: part.text
|
|
2555
|
-
};
|
|
2556
|
-
}
|
|
2557
|
-
else if (part.inlineData) {
|
|
2558
|
-
const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
|
|
2559
|
-
const imageBlob = await formattedImageContent.blob();
|
|
2560
|
-
const imageBitmap = await createImageBitmap(imageBlob);
|
|
2561
|
-
return {
|
|
2562
|
-
type: 'image',
|
|
2563
|
-
value: imageBitmap
|
|
2564
|
-
};
|
|
2565
|
-
}
|
|
2566
|
-
throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
|
|
2439
|
+
static anyOf(anyOfParams) {
|
|
2440
|
+
return new AnyOfSchema(anyOfParams);
|
|
2567
2441
|
}
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
* inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
|
|
2580
|
-
* inference.
|
|
2581
|
-
*
|
|
2582
|
-
* Chrome will remove a model from memory if it's no longer in use, so this method ensures a
|
|
2583
|
-
* new session is created before an old session is destroyed.
|
|
2584
|
-
*/
|
|
2585
|
-
async createSession() {
|
|
2586
|
-
if (!this.languageModelProvider) {
|
|
2587
|
-
throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
|
|
2588
|
-
}
|
|
2589
|
-
const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
|
|
2590
|
-
if (this.oldSession) {
|
|
2591
|
-
this.oldSession.destroy();
|
|
2592
|
-
}
|
|
2593
|
-
// Holds session reference, so model isn't unloaded from memory.
|
|
2594
|
-
this.oldSession = newSession;
|
|
2595
|
-
return newSession;
|
|
2596
|
-
}
|
|
2597
|
-
/**
|
|
2598
|
-
* Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
|
|
2599
|
-
*/
|
|
2600
|
-
static toResponse(text) {
|
|
2601
|
-
return {
|
|
2602
|
-
json: async () => ({
|
|
2603
|
-
candidates: [
|
|
2604
|
-
{
|
|
2605
|
-
content: {
|
|
2606
|
-
parts: [{ text }]
|
|
2607
|
-
}
|
|
2608
|
-
}
|
|
2609
|
-
]
|
|
2610
|
-
})
|
|
2611
|
-
};
|
|
2612
|
-
}
|
|
2613
|
-
/**
|
|
2614
|
-
* Formats string stream returned by Chrome as SSE returned by Firebase AI.
|
|
2615
|
-
*/
|
|
2616
|
-
static toStreamResponse(stream) {
|
|
2617
|
-
const encoder = new TextEncoder();
|
|
2618
|
-
return {
|
|
2619
|
-
body: stream.pipeThrough(new TransformStream({
|
|
2620
|
-
transform(chunk, controller) {
|
|
2621
|
-
const json = JSON.stringify({
|
|
2622
|
-
candidates: [
|
|
2623
|
-
{
|
|
2624
|
-
content: {
|
|
2625
|
-
role: 'model',
|
|
2626
|
-
parts: [{ text: chunk }]
|
|
2627
|
-
}
|
|
2628
|
-
}
|
|
2629
|
-
]
|
|
2630
|
-
});
|
|
2631
|
-
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
|
2632
|
-
}
|
|
2633
|
-
}))
|
|
2634
|
-
};
|
|
2635
|
-
}
|
|
2636
|
-
}
|
|
2637
|
-
// Visible for testing
|
|
2638
|
-
ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
|
|
2639
|
-
|
|
2640
|
-
/**
|
|
2641
|
-
* @license
|
|
2642
|
-
* Copyright 2024 Google LLC
|
|
2643
|
-
*
|
|
2644
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2645
|
-
* you may not use this file except in compliance with the License.
|
|
2646
|
-
* You may obtain a copy of the License at
|
|
2647
|
-
*
|
|
2648
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2649
|
-
*
|
|
2650
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
2651
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2652
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2653
|
-
* See the License for the specific language governing permissions and
|
|
2654
|
-
* limitations under the License.
|
|
2655
|
-
*/
|
|
2656
|
-
/**
|
|
2657
|
-
* Parent class encompassing all Schema types, with static methods that
|
|
2658
|
-
* allow building specific Schema types. This class can be converted with
|
|
2659
|
-
* `JSON.stringify()` into a JSON string accepted by Vertex AI REST endpoints.
|
|
2660
|
-
* (This string conversion is automatically done when calling SDK methods.)
|
|
2661
|
-
* @public
|
|
2662
|
-
*/
|
|
2663
|
-
class Schema {
|
|
2664
|
-
constructor(schemaParams) {
|
|
2665
|
-
// TODO(dlarocque): Enforce this with union types
|
|
2666
|
-
if (!schemaParams.type && !schemaParams.anyOf) {
|
|
2667
|
-
throw new AIError(AIErrorCode.INVALID_SCHEMA, "A schema must have either a 'type' or an 'anyOf' array of sub-schemas.");
|
|
2668
|
-
}
|
|
2669
|
-
// eslint-disable-next-line guard-for-in
|
|
2670
|
-
for (const paramKey in schemaParams) {
|
|
2671
|
-
this[paramKey] = schemaParams[paramKey];
|
|
2672
|
-
}
|
|
2673
|
-
// Ensure these are explicitly set to avoid TS errors.
|
|
2674
|
-
this.type = schemaParams.type;
|
|
2675
|
-
this.format = schemaParams.hasOwnProperty('format')
|
|
2676
|
-
? schemaParams.format
|
|
2677
|
-
: undefined;
|
|
2678
|
-
this.nullable = schemaParams.hasOwnProperty('nullable')
|
|
2679
|
-
? !!schemaParams.nullable
|
|
2680
|
-
: false;
|
|
2681
|
-
}
|
|
2682
|
-
/**
|
|
2683
|
-
* Defines how this Schema should be serialized as JSON.
|
|
2684
|
-
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior
|
|
2685
|
-
* @internal
|
|
2686
|
-
*/
|
|
2687
|
-
toJSON() {
|
|
2688
|
-
const obj = {
|
|
2689
|
-
type: this.type
|
|
2690
|
-
};
|
|
2691
|
-
for (const prop in this) {
|
|
2692
|
-
if (this.hasOwnProperty(prop) && this[prop] !== undefined) {
|
|
2693
|
-
if (prop !== 'required' || this.type === SchemaType.OBJECT) {
|
|
2694
|
-
obj[prop] = this[prop];
|
|
2695
|
-
}
|
|
2696
|
-
}
|
|
2697
|
-
}
|
|
2698
|
-
return obj;
|
|
2699
|
-
}
|
|
2700
|
-
static array(arrayParams) {
|
|
2701
|
-
return new ArraySchema(arrayParams, arrayParams.items);
|
|
2702
|
-
}
|
|
2703
|
-
static object(objectParams) {
|
|
2704
|
-
return new ObjectSchema(objectParams, objectParams.properties, objectParams.optionalProperties);
|
|
2705
|
-
}
|
|
2706
|
-
// eslint-disable-next-line id-blacklist
|
|
2707
|
-
static string(stringParams) {
|
|
2708
|
-
return new StringSchema(stringParams);
|
|
2709
|
-
}
|
|
2710
|
-
static enumString(stringParams) {
|
|
2711
|
-
return new StringSchema(stringParams, stringParams.enum);
|
|
2712
|
-
}
|
|
2713
|
-
static integer(integerParams) {
|
|
2714
|
-
return new IntegerSchema(integerParams);
|
|
2715
|
-
}
|
|
2716
|
-
// eslint-disable-next-line id-blacklist
|
|
2717
|
-
static number(numberParams) {
|
|
2718
|
-
return new NumberSchema(numberParams);
|
|
2719
|
-
}
|
|
2720
|
-
// eslint-disable-next-line id-blacklist
|
|
2721
|
-
static boolean(booleanParams) {
|
|
2722
|
-
return new BooleanSchema(booleanParams);
|
|
2723
|
-
}
|
|
2724
|
-
static anyOf(anyOfParams) {
|
|
2725
|
-
return new AnyOfSchema(anyOfParams);
|
|
2726
|
-
}
|
|
2727
|
-
}
|
|
2728
|
-
/**
|
|
2729
|
-
* Schema class for "integer" types.
|
|
2730
|
-
* @public
|
|
2731
|
-
*/
|
|
2732
|
-
class IntegerSchema extends Schema {
|
|
2733
|
-
constructor(schemaParams) {
|
|
2734
|
-
super({
|
|
2735
|
-
type: SchemaType.INTEGER,
|
|
2736
|
-
...schemaParams
|
|
2737
|
-
});
|
|
2442
|
+
}
|
|
2443
|
+
/**
|
|
2444
|
+
* Schema class for "integer" types.
|
|
2445
|
+
* @public
|
|
2446
|
+
*/
|
|
2447
|
+
class IntegerSchema extends Schema {
|
|
2448
|
+
constructor(schemaParams) {
|
|
2449
|
+
super({
|
|
2450
|
+
type: SchemaType.INTEGER,
|
|
2451
|
+
...schemaParams
|
|
2452
|
+
});
|
|
2738
2453
|
}
|
|
2739
2454
|
}
|
|
2740
2455
|
/**
|
|
@@ -3024,11 +2739,11 @@ function getGenerativeModel(ai, modelParams, requestOptions) {
|
|
|
3024
2739
|
if (!inCloudParams.model) {
|
|
3025
2740
|
throw new AIError(AIErrorCode.NO_MODEL, `Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })`);
|
|
3026
2741
|
}
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
2742
|
+
/**
|
|
2743
|
+
* An AIService registered by index.node.ts will not have a
|
|
2744
|
+
* chromeAdapterFactory() method.
|
|
2745
|
+
*/
|
|
2746
|
+
const chromeAdapter = ai.chromeAdapterFactory?.(hybridParams.mode, typeof window === 'undefined' ? undefined : window, hybridParams.onDeviceParams);
|
|
3032
2747
|
return new GenerativeModel(ai, inCloudParams, requestOptions, chromeAdapter);
|
|
3033
2748
|
}
|
|
3034
2749
|
/**
|
|
@@ -3052,6 +2767,301 @@ function getImagenModel(ai, modelParams, requestOptions) {
|
|
|
3052
2767
|
return new ImagenModel(ai, modelParams, requestOptions);
|
|
3053
2768
|
}
|
|
3054
2769
|
|
|
2770
|
+
/**
|
|
2771
|
+
* @internal
|
|
2772
|
+
*/
|
|
2773
|
+
var Availability;
|
|
2774
|
+
(function (Availability) {
|
|
2775
|
+
Availability["UNAVAILABLE"] = "unavailable";
|
|
2776
|
+
Availability["DOWNLOADABLE"] = "downloadable";
|
|
2777
|
+
Availability["DOWNLOADING"] = "downloading";
|
|
2778
|
+
Availability["AVAILABLE"] = "available";
|
|
2779
|
+
})(Availability || (Availability = {}));
|
|
2780
|
+
|
|
2781
|
+
/**
|
|
2782
|
+
* @license
|
|
2783
|
+
* Copyright 2025 Google LLC
|
|
2784
|
+
*
|
|
2785
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2786
|
+
* you may not use this file except in compliance with the License.
|
|
2787
|
+
* You may obtain a copy of the License at
|
|
2788
|
+
*
|
|
2789
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2790
|
+
*
|
|
2791
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2792
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2793
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2794
|
+
* See the License for the specific language governing permissions and
|
|
2795
|
+
* limitations under the License.
|
|
2796
|
+
*/
|
|
2797
|
+
/**
|
|
2798
|
+
* Defines an inference "backend" that uses Chrome's on-device model,
|
|
2799
|
+
* and encapsulates logic for detecting when on-device inference is
|
|
2800
|
+
* possible.
|
|
2801
|
+
*/
|
|
2802
|
+
class ChromeAdapterImpl {
|
|
2803
|
+
constructor(languageModelProvider, mode, onDeviceParams = {
|
|
2804
|
+
createOptions: {
|
|
2805
|
+
// Defaults to support image inputs for convenience.
|
|
2806
|
+
expectedInputs: [{ type: 'image' }]
|
|
2807
|
+
}
|
|
2808
|
+
}) {
|
|
2809
|
+
this.languageModelProvider = languageModelProvider;
|
|
2810
|
+
this.mode = mode;
|
|
2811
|
+
this.onDeviceParams = onDeviceParams;
|
|
2812
|
+
this.isDownloading = false;
|
|
2813
|
+
}
|
|
2814
|
+
/**
|
|
2815
|
+
* Checks if a given request can be made on-device.
|
|
2816
|
+
*
|
|
2817
|
+
* Encapsulates a few concerns:
|
|
2818
|
+
* the mode
|
|
2819
|
+
* API existence
|
|
2820
|
+
* prompt formatting
|
|
2821
|
+
* model availability, including triggering download if necessary
|
|
2822
|
+
*
|
|
2823
|
+
*
|
|
2824
|
+
* Pros: callers needn't be concerned with details of on-device availability.</p>
|
|
2825
|
+
* Cons: this method spans a few concerns and splits request validation from usage.
|
|
2826
|
+
* If instance variables weren't already part of the API, we could consider a better
|
|
2827
|
+
* separation of concerns.
|
|
2828
|
+
*/
|
|
2829
|
+
async isAvailable(request) {
|
|
2830
|
+
if (!this.mode) {
|
|
2831
|
+
logger.debug(`On-device inference unavailable because mode is undefined.`);
|
|
2832
|
+
return false;
|
|
2833
|
+
}
|
|
2834
|
+
if (this.mode === InferenceMode.ONLY_IN_CLOUD) {
|
|
2835
|
+
logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
|
|
2836
|
+
return false;
|
|
2837
|
+
}
|
|
2838
|
+
// Triggers out-of-band download so model will eventually become available.
|
|
2839
|
+
const availability = await this.downloadIfAvailable();
|
|
2840
|
+
if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
|
|
2841
|
+
// If it will never be available due to API inavailability, throw.
|
|
2842
|
+
if (availability === Availability.UNAVAILABLE) {
|
|
2843
|
+
throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
|
|
2844
|
+
}
|
|
2845
|
+
else if (availability === Availability.DOWNLOADABLE ||
|
|
2846
|
+
availability === Availability.DOWNLOADING) {
|
|
2847
|
+
// TODO(chholland): Better user experience during download - progress?
|
|
2848
|
+
logger.debug(`Waiting for download of LanguageModel to complete.`);
|
|
2849
|
+
await this.downloadPromise;
|
|
2850
|
+
return true;
|
|
2851
|
+
}
|
|
2852
|
+
return true;
|
|
2853
|
+
}
|
|
2854
|
+
// Applies prefer_on_device logic.
|
|
2855
|
+
if (availability !== Availability.AVAILABLE) {
|
|
2856
|
+
logger.debug(`On-device inference unavailable because availability is "${availability}".`);
|
|
2857
|
+
return false;
|
|
2858
|
+
}
|
|
2859
|
+
if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
|
|
2860
|
+
logger.debug(`On-device inference unavailable because request is incompatible.`);
|
|
2861
|
+
return false;
|
|
2862
|
+
}
|
|
2863
|
+
return true;
|
|
2864
|
+
}
|
|
2865
|
+
/**
|
|
2866
|
+
* Generates content on device.
|
|
2867
|
+
*
|
|
2868
|
+
* @remarks
|
|
2869
|
+
* This is comparable to {@link GenerativeModel.generateContent} for generating content in
|
|
2870
|
+
* Cloud.
|
|
2871
|
+
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
2872
|
+
* @returns {@link Response}, so we can reuse common response formatting.
|
|
2873
|
+
*/
|
|
2874
|
+
async generateContent(request) {
|
|
2875
|
+
const session = await this.createSession();
|
|
2876
|
+
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
2877
|
+
const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
|
|
2878
|
+
return ChromeAdapterImpl.toResponse(text);
|
|
2879
|
+
}
|
|
2880
|
+
/**
|
|
2881
|
+
* Generates content stream on device.
|
|
2882
|
+
*
|
|
2883
|
+
* @remarks
|
|
2884
|
+
* This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
|
|
2885
|
+
* Cloud.
|
|
2886
|
+
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
2887
|
+
* @returns {@link Response}, so we can reuse common response formatting.
|
|
2888
|
+
*/
|
|
2889
|
+
async generateContentStream(request) {
|
|
2890
|
+
const session = await this.createSession();
|
|
2891
|
+
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
2892
|
+
const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
|
|
2893
|
+
return ChromeAdapterImpl.toStreamResponse(stream);
|
|
2894
|
+
}
|
|
2895
|
+
async countTokens(_request) {
|
|
2896
|
+
throw new AIError(AIErrorCode.REQUEST_ERROR, 'Count Tokens is not yet available for on-device model.');
|
|
2897
|
+
}
|
|
2898
|
+
/**
|
|
2899
|
+
* Asserts inference for the given request can be performed by an on-device model.
|
|
2900
|
+
*/
|
|
2901
|
+
static isOnDeviceRequest(request) {
|
|
2902
|
+
// Returns false if the prompt is empty.
|
|
2903
|
+
if (request.contents.length === 0) {
|
|
2904
|
+
logger.debug('Empty prompt rejected for on-device inference.');
|
|
2905
|
+
return false;
|
|
2906
|
+
}
|
|
2907
|
+
for (const content of request.contents) {
|
|
2908
|
+
if (content.role === 'function') {
|
|
2909
|
+
logger.debug(`"Function" role rejected for on-device inference.`);
|
|
2910
|
+
return false;
|
|
2911
|
+
}
|
|
2912
|
+
// Returns false if request contains an image with an unsupported mime type.
|
|
2913
|
+
for (const part of content.parts) {
|
|
2914
|
+
if (part.inlineData &&
|
|
2915
|
+
ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
|
|
2916
|
+
logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
|
|
2917
|
+
return false;
|
|
2918
|
+
}
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
return true;
|
|
2922
|
+
}
|
|
2923
|
+
/**
|
|
2924
|
+
* Encapsulates logic to get availability and download a model if one is downloadable.
|
|
2925
|
+
*/
|
|
2926
|
+
async downloadIfAvailable() {
|
|
2927
|
+
const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
|
|
2928
|
+
if (availability === Availability.DOWNLOADABLE) {
|
|
2929
|
+
this.download();
|
|
2930
|
+
}
|
|
2931
|
+
return availability;
|
|
2932
|
+
}
|
|
2933
|
+
/**
|
|
2934
|
+
* Triggers out-of-band download of an on-device model.
|
|
2935
|
+
*
|
|
2936
|
+
* Chrome only downloads models as needed. Chrome knows a model is needed when code calls
|
|
2937
|
+
* LanguageModel.create.
|
|
2938
|
+
*
|
|
2939
|
+
* Since Chrome manages the download, the SDK can only avoid redundant download requests by
|
|
2940
|
+
* tracking if a download has previously been requested.
|
|
2941
|
+
*/
|
|
2942
|
+
download() {
|
|
2943
|
+
if (this.isDownloading) {
|
|
2944
|
+
return;
|
|
2945
|
+
}
|
|
2946
|
+
this.isDownloading = true;
|
|
2947
|
+
this.downloadPromise = this.languageModelProvider
|
|
2948
|
+
?.create(this.onDeviceParams.createOptions)
|
|
2949
|
+
.finally(() => {
|
|
2950
|
+
this.isDownloading = false;
|
|
2951
|
+
});
|
|
2952
|
+
}
|
|
2953
|
+
/**
|
|
2954
|
+
* Converts Firebase AI {@link Content} object to a Chrome {@link LanguageModelMessage} object.
|
|
2955
|
+
*/
|
|
2956
|
+
static async toLanguageModelMessage(content) {
|
|
2957
|
+
const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
|
|
2958
|
+
return {
|
|
2959
|
+
role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
|
|
2960
|
+
content: languageModelMessageContents
|
|
2961
|
+
};
|
|
2962
|
+
}
|
|
2963
|
+
/**
|
|
2964
|
+
* Converts a Firebase AI Part object to a Chrome LanguageModelMessageContent object.
|
|
2965
|
+
*/
|
|
2966
|
+
static async toLanguageModelMessageContent(part) {
|
|
2967
|
+
if (part.text) {
|
|
2968
|
+
return {
|
|
2969
|
+
type: 'text',
|
|
2970
|
+
value: part.text
|
|
2971
|
+
};
|
|
2972
|
+
}
|
|
2973
|
+
else if (part.inlineData) {
|
|
2974
|
+
const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
|
|
2975
|
+
const imageBlob = await formattedImageContent.blob();
|
|
2976
|
+
const imageBitmap = await createImageBitmap(imageBlob);
|
|
2977
|
+
return {
|
|
2978
|
+
type: 'image',
|
|
2979
|
+
value: imageBitmap
|
|
2980
|
+
};
|
|
2981
|
+
}
|
|
2982
|
+
throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
|
|
2983
|
+
}
|
|
2984
|
+
/**
|
|
2985
|
+
* Converts a Firebase AI {@link Role} string to a {@link LanguageModelMessageRole} string.
|
|
2986
|
+
*/
|
|
2987
|
+
static toLanguageModelMessageRole(role) {
|
|
2988
|
+
// Assumes 'function' rule has been filtered by isOnDeviceRequest
|
|
2989
|
+
return role === 'model' ? 'assistant' : 'user';
|
|
2990
|
+
}
|
|
2991
|
+
/**
|
|
2992
|
+
* Abstracts Chrome session creation.
|
|
2993
|
+
*
|
|
2994
|
+
* Chrome uses a multi-turn session for all inference. Firebase AI uses single-turn for all
|
|
2995
|
+
* inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
|
|
2996
|
+
* inference.
|
|
2997
|
+
*
|
|
2998
|
+
* Chrome will remove a model from memory if it's no longer in use, so this method ensures a
|
|
2999
|
+
* new session is created before an old session is destroyed.
|
|
3000
|
+
*/
|
|
3001
|
+
async createSession() {
|
|
3002
|
+
if (!this.languageModelProvider) {
|
|
3003
|
+
throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
|
|
3004
|
+
}
|
|
3005
|
+
const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
|
|
3006
|
+
if (this.oldSession) {
|
|
3007
|
+
this.oldSession.destroy();
|
|
3008
|
+
}
|
|
3009
|
+
// Holds session reference, so model isn't unloaded from memory.
|
|
3010
|
+
this.oldSession = newSession;
|
|
3011
|
+
return newSession;
|
|
3012
|
+
}
|
|
3013
|
+
/**
|
|
3014
|
+
* Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
|
|
3015
|
+
*/
|
|
3016
|
+
static toResponse(text) {
|
|
3017
|
+
return {
|
|
3018
|
+
json: async () => ({
|
|
3019
|
+
candidates: [
|
|
3020
|
+
{
|
|
3021
|
+
content: {
|
|
3022
|
+
parts: [{ text }]
|
|
3023
|
+
}
|
|
3024
|
+
}
|
|
3025
|
+
]
|
|
3026
|
+
})
|
|
3027
|
+
};
|
|
3028
|
+
}
|
|
3029
|
+
/**
|
|
3030
|
+
* Formats string stream returned by Chrome as SSE returned by Firebase AI.
|
|
3031
|
+
*/
|
|
3032
|
+
static toStreamResponse(stream) {
|
|
3033
|
+
const encoder = new TextEncoder();
|
|
3034
|
+
return {
|
|
3035
|
+
body: stream.pipeThrough(new TransformStream({
|
|
3036
|
+
transform(chunk, controller) {
|
|
3037
|
+
const json = JSON.stringify({
|
|
3038
|
+
candidates: [
|
|
3039
|
+
{
|
|
3040
|
+
content: {
|
|
3041
|
+
role: 'model',
|
|
3042
|
+
parts: [{ text: chunk }]
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
]
|
|
3046
|
+
});
|
|
3047
|
+
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
|
3048
|
+
}
|
|
3049
|
+
}))
|
|
3050
|
+
};
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
// Visible for testing
|
|
3054
|
+
ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
|
|
3055
|
+
/**
|
|
3056
|
+
* Creates a ChromeAdapterImpl on demand.
|
|
3057
|
+
*/
|
|
3058
|
+
function chromeAdapterFactory(mode, window, params) {
|
|
3059
|
+
// Do not initialize a ChromeAdapter if we are not in hybrid mode.
|
|
3060
|
+
if (typeof window !== 'undefined' && mode) {
|
|
3061
|
+
return new ChromeAdapterImpl(window.LanguageModel, mode, params);
|
|
3062
|
+
}
|
|
3063
|
+
}
|
|
3064
|
+
|
|
3055
3065
|
/**
|
|
3056
3066
|
* The Firebase AI Web SDK.
|
|
3057
3067
|
*
|
|
@@ -3066,7 +3076,7 @@ function factory(container, { instanceIdentifier }) {
|
|
|
3066
3076
|
const app = container.getProvider('app').getImmediate();
|
|
3067
3077
|
const auth = container.getProvider('auth-internal');
|
|
3068
3078
|
const appCheckProvider = container.getProvider('app-check-internal');
|
|
3069
|
-
return new AIService(app, backend, auth, appCheckProvider);
|
|
3079
|
+
return new AIService(app, backend, auth, appCheckProvider, chromeAdapterFactory);
|
|
3070
3080
|
}
|
|
3071
3081
|
function registerAI() {
|
|
3072
3082
|
app._registerComponent(new component.Component(AI_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
|