@firebase/ai 2.2.0 → 2.2.1-canary.06ab5c4f9
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 +19 -138
- package/dist/ai.d.ts +19 -175
- package/dist/esm/index.esm.js +604 -515
- package/dist/esm/index.esm.js.map +1 -1
- package/dist/esm/src/factory-browser.d.ts +19 -0
- package/dist/esm/src/index.d.ts +0 -3
- package/dist/esm/src/requests/hybrid-helpers.d.ts +28 -0
- package/dist/esm/src/types/enums.d.ts +19 -0
- package/dist/index.cjs.js +603 -515
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.node.cjs.js +90 -18
- package/dist/index.node.cjs.js.map +1 -1
- package/dist/index.node.mjs +90 -18
- package/dist/index.node.mjs.map +1 -1
- package/dist/src/factory-browser.d.ts +19 -0
- package/dist/src/index.d.ts +0 -3
- package/dist/src/requests/hybrid-helpers.d.ts +28 -0
- package/dist/src/types/enums.d.ts +19 -0
- package/package.json +10 -9
package/dist/esm/index.esm.js
CHANGED
|
@@ -4,7 +4,7 @@ import { FirebaseError, Deferred, getModularInstance } from '@firebase/util';
|
|
|
4
4
|
import { Logger } from '@firebase/logger';
|
|
5
5
|
|
|
6
6
|
var name = "@firebase/ai";
|
|
7
|
-
var version = "2.2.
|
|
7
|
+
var version = "2.2.1-canary.06ab5c4f9";
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* @license
|
|
@@ -34,6 +34,62 @@ const DEFAULT_FETCH_TIMEOUT_MS = 180 * 1000;
|
|
|
34
34
|
*/
|
|
35
35
|
const DEFAULT_HYBRID_IN_CLOUD_MODEL = 'gemini-2.0-flash-lite';
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* @license
|
|
39
|
+
* Copyright 2024 Google LLC
|
|
40
|
+
*
|
|
41
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
42
|
+
* you may not use this file except in compliance with the License.
|
|
43
|
+
* You may obtain a copy of the License at
|
|
44
|
+
*
|
|
45
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
46
|
+
*
|
|
47
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
48
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
49
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
50
|
+
* See the License for the specific language governing permissions and
|
|
51
|
+
* limitations under the License.
|
|
52
|
+
*/
|
|
53
|
+
/**
|
|
54
|
+
* Error class for the Firebase AI SDK.
|
|
55
|
+
*
|
|
56
|
+
* @public
|
|
57
|
+
*/
|
|
58
|
+
class AIError extends FirebaseError {
|
|
59
|
+
/**
|
|
60
|
+
* Constructs a new instance of the `AIError` class.
|
|
61
|
+
*
|
|
62
|
+
* @param code - The error code from {@link (AIErrorCode:type)}.
|
|
63
|
+
* @param message - A human-readable message describing the error.
|
|
64
|
+
* @param customErrorData - Optional error data.
|
|
65
|
+
*/
|
|
66
|
+
constructor(code, message, customErrorData) {
|
|
67
|
+
// Match error format used by FirebaseError from ErrorFactory
|
|
68
|
+
const service = AI_TYPE;
|
|
69
|
+
const fullCode = `${service}/${code}`;
|
|
70
|
+
const fullMessage = `${service}: ${message} (${fullCode})`;
|
|
71
|
+
super(code, fullMessage);
|
|
72
|
+
this.code = code;
|
|
73
|
+
this.customErrorData = customErrorData;
|
|
74
|
+
// FirebaseError initializes a stack trace, but it assumes the error is created from the error
|
|
75
|
+
// factory. Since we break this assumption, we set the stack trace to be originating from this
|
|
76
|
+
// constructor.
|
|
77
|
+
// This is only supported in V8.
|
|
78
|
+
if (Error.captureStackTrace) {
|
|
79
|
+
// Allows us to initialize the stack trace without including the constructor itself at the
|
|
80
|
+
// top level of the stack trace.
|
|
81
|
+
Error.captureStackTrace(this, AIError);
|
|
82
|
+
}
|
|
83
|
+
// Allows instanceof AIError in ES5/ES6
|
|
84
|
+
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
|
|
85
|
+
// TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
|
|
86
|
+
// which we can now use since we no longer target ES5.
|
|
87
|
+
Object.setPrototypeOf(this, AIError.prototype);
|
|
88
|
+
// Since Error is an interface, we don't inherit toString and so we define it ourselves.
|
|
89
|
+
this.toString = () => fullMessage;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
37
93
|
/**
|
|
38
94
|
* @license
|
|
39
95
|
* Copyright 2024 Google LLC
|
|
@@ -299,12 +355,30 @@ const ResponseModality = {
|
|
|
299
355
|
/**
|
|
300
356
|
* <b>(EXPERIMENTAL)</b>
|
|
301
357
|
* Determines whether inference happens on-device or in-cloud.
|
|
358
|
+
*
|
|
359
|
+
* @remarks
|
|
360
|
+
* <b>PREFER_ON_DEVICE:</b> Attempt to make inference calls using an
|
|
361
|
+
* on-device model. If on-device inference is not available, the SDK
|
|
362
|
+
* will fall back to using a cloud-hosted model.
|
|
363
|
+
* <br/>
|
|
364
|
+
* <b>ONLY_ON_DEVICE:</b> Only attempt to make inference calls using an
|
|
365
|
+
* on-device model. The SDK will not fall back to a cloud-hosted model.
|
|
366
|
+
* If on-device inference is not available, inference methods will throw.
|
|
367
|
+
* <br/>
|
|
368
|
+
* <b>ONLY_IN_CLOUD:</b> Only attempt to make inference calls using a
|
|
369
|
+
* cloud-hosted model. The SDK will not fall back to an on-device model.
|
|
370
|
+
* <br/>
|
|
371
|
+
* <b>PREFER_IN_CLOUD:</b> Attempt to make inference calls to a
|
|
372
|
+
* cloud-hosted model. If not available, the SDK will fall back to an
|
|
373
|
+
* on-device model.
|
|
374
|
+
*
|
|
302
375
|
* @public
|
|
303
376
|
*/
|
|
304
377
|
const InferenceMode = {
|
|
305
378
|
'PREFER_ON_DEVICE': 'prefer_on_device',
|
|
306
379
|
'ONLY_ON_DEVICE': 'only_on_device',
|
|
307
|
-
'ONLY_IN_CLOUD': 'only_in_cloud'
|
|
380
|
+
'ONLY_IN_CLOUD': 'only_in_cloud',
|
|
381
|
+
'PREFER_IN_CLOUD': 'prefer_in_cloud'
|
|
308
382
|
};
|
|
309
383
|
|
|
310
384
|
/**
|
|
@@ -653,105 +727,6 @@ class VertexAIBackend extends Backend {
|
|
|
653
727
|
}
|
|
654
728
|
}
|
|
655
729
|
|
|
656
|
-
/**
|
|
657
|
-
* @license
|
|
658
|
-
* Copyright 2024 Google LLC
|
|
659
|
-
*
|
|
660
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
661
|
-
* you may not use this file except in compliance with the License.
|
|
662
|
-
* You may obtain a copy of the License at
|
|
663
|
-
*
|
|
664
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
665
|
-
*
|
|
666
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
667
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
668
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
669
|
-
* See the License for the specific language governing permissions and
|
|
670
|
-
* limitations under the License.
|
|
671
|
-
*/
|
|
672
|
-
class AIService {
|
|
673
|
-
constructor(app, backend, authProvider, appCheckProvider, chromeAdapterFactory) {
|
|
674
|
-
this.app = app;
|
|
675
|
-
this.backend = backend;
|
|
676
|
-
this.chromeAdapterFactory = chromeAdapterFactory;
|
|
677
|
-
const appCheck = appCheckProvider?.getImmediate({ optional: true });
|
|
678
|
-
const auth = authProvider?.getImmediate({ optional: true });
|
|
679
|
-
this.auth = auth || null;
|
|
680
|
-
this.appCheck = appCheck || null;
|
|
681
|
-
if (backend instanceof VertexAIBackend) {
|
|
682
|
-
this.location = backend.location;
|
|
683
|
-
}
|
|
684
|
-
else {
|
|
685
|
-
this.location = '';
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
_delete() {
|
|
689
|
-
return Promise.resolve();
|
|
690
|
-
}
|
|
691
|
-
set options(optionsToSet) {
|
|
692
|
-
this._options = optionsToSet;
|
|
693
|
-
}
|
|
694
|
-
get options() {
|
|
695
|
-
return this._options;
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
/**
|
|
700
|
-
* @license
|
|
701
|
-
* Copyright 2024 Google LLC
|
|
702
|
-
*
|
|
703
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
704
|
-
* you may not use this file except in compliance with the License.
|
|
705
|
-
* You may obtain a copy of the License at
|
|
706
|
-
*
|
|
707
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
708
|
-
*
|
|
709
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
710
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
711
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
712
|
-
* See the License for the specific language governing permissions and
|
|
713
|
-
* limitations under the License.
|
|
714
|
-
*/
|
|
715
|
-
/**
|
|
716
|
-
* Error class for the Firebase AI SDK.
|
|
717
|
-
*
|
|
718
|
-
* @public
|
|
719
|
-
*/
|
|
720
|
-
class AIError extends FirebaseError {
|
|
721
|
-
/**
|
|
722
|
-
* Constructs a new instance of the `AIError` class.
|
|
723
|
-
*
|
|
724
|
-
* @param code - The error code from {@link (AIErrorCode:type)}.
|
|
725
|
-
* @param message - A human-readable message describing the error.
|
|
726
|
-
* @param customErrorData - Optional error data.
|
|
727
|
-
*/
|
|
728
|
-
constructor(code, message, customErrorData) {
|
|
729
|
-
// Match error format used by FirebaseError from ErrorFactory
|
|
730
|
-
const service = AI_TYPE;
|
|
731
|
-
const fullCode = `${service}/${code}`;
|
|
732
|
-
const fullMessage = `${service}: ${message} (${fullCode})`;
|
|
733
|
-
super(code, fullMessage);
|
|
734
|
-
this.code = code;
|
|
735
|
-
this.customErrorData = customErrorData;
|
|
736
|
-
// FirebaseError initializes a stack trace, but it assumes the error is created from the error
|
|
737
|
-
// factory. Since we break this assumption, we set the stack trace to be originating from this
|
|
738
|
-
// constructor.
|
|
739
|
-
// This is only supported in V8.
|
|
740
|
-
if (Error.captureStackTrace) {
|
|
741
|
-
// Allows us to initialize the stack trace without including the constructor itself at the
|
|
742
|
-
// top level of the stack trace.
|
|
743
|
-
Error.captureStackTrace(this, AIError);
|
|
744
|
-
}
|
|
745
|
-
// Allows instanceof AIError in ES5/ES6
|
|
746
|
-
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
|
|
747
|
-
// TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
|
|
748
|
-
// which we can now use since we no longer target ES5.
|
|
749
|
-
Object.setPrototypeOf(this, AIError.prototype);
|
|
750
|
-
// Since Error is an interface, we don't inherit toString and so we define it ourselves.
|
|
751
|
-
this.toString = () => fullMessage;
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
|
|
755
730
|
/**
|
|
756
731
|
* @license
|
|
757
732
|
* Copyright 2025 Google LLC
|
|
@@ -812,7 +787,7 @@ function decodeInstanceIdentifier(instanceIdentifier) {
|
|
|
812
787
|
|
|
813
788
|
/**
|
|
814
789
|
* @license
|
|
815
|
-
* Copyright
|
|
790
|
+
* Copyright 2024 Google LLC
|
|
816
791
|
*
|
|
817
792
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
818
793
|
* you may not use this file except in compliance with the License.
|
|
@@ -826,113 +801,300 @@ function decodeInstanceIdentifier(instanceIdentifier) {
|
|
|
826
801
|
* See the License for the specific language governing permissions and
|
|
827
802
|
* limitations under the License.
|
|
828
803
|
*/
|
|
804
|
+
const logger = new Logger('@firebase/vertexai');
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* @internal
|
|
808
|
+
*/
|
|
809
|
+
var Availability;
|
|
810
|
+
(function (Availability) {
|
|
811
|
+
Availability["UNAVAILABLE"] = "unavailable";
|
|
812
|
+
Availability["DOWNLOADABLE"] = "downloadable";
|
|
813
|
+
Availability["DOWNLOADING"] = "downloading";
|
|
814
|
+
Availability["AVAILABLE"] = "available";
|
|
815
|
+
})(Availability || (Availability = {}));
|
|
816
|
+
|
|
829
817
|
/**
|
|
830
|
-
*
|
|
818
|
+
* @license
|
|
819
|
+
* Copyright 2025 Google LLC
|
|
831
820
|
*
|
|
832
|
-
*
|
|
833
|
-
*
|
|
821
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
822
|
+
* you may not use this file except in compliance with the License.
|
|
823
|
+
* You may obtain a copy of the License at
|
|
834
824
|
*
|
|
835
|
-
*
|
|
825
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
826
|
+
*
|
|
827
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
828
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
829
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
830
|
+
* See the License for the specific language governing permissions and
|
|
831
|
+
* limitations under the License.
|
|
836
832
|
*/
|
|
837
|
-
|
|
833
|
+
/**
|
|
834
|
+
* Defines an inference "backend" that uses Chrome's on-device model,
|
|
835
|
+
* and encapsulates logic for detecting when on-device inference is
|
|
836
|
+
* possible.
|
|
837
|
+
*/
|
|
838
|
+
class ChromeAdapterImpl {
|
|
839
|
+
constructor(languageModelProvider, mode, onDeviceParams = {
|
|
840
|
+
createOptions: {
|
|
841
|
+
// Defaults to support image inputs for convenience.
|
|
842
|
+
expectedInputs: [{ type: 'image' }]
|
|
843
|
+
}
|
|
844
|
+
}) {
|
|
845
|
+
this.languageModelProvider = languageModelProvider;
|
|
846
|
+
this.mode = mode;
|
|
847
|
+
this.onDeviceParams = onDeviceParams;
|
|
848
|
+
this.isDownloading = false;
|
|
849
|
+
}
|
|
838
850
|
/**
|
|
839
|
-
*
|
|
840
|
-
*
|
|
841
|
-
* This constructor should only be called from subclasses that provide
|
|
842
|
-
* a model API.
|
|
851
|
+
* Checks if a given request can be made on-device.
|
|
843
852
|
*
|
|
844
|
-
*
|
|
845
|
-
*
|
|
846
|
-
*
|
|
847
|
-
*
|
|
848
|
-
*
|
|
853
|
+
* Encapsulates a few concerns:
|
|
854
|
+
* the mode
|
|
855
|
+
* API existence
|
|
856
|
+
* prompt formatting
|
|
857
|
+
* model availability, including triggering download if necessary
|
|
849
858
|
*
|
|
850
|
-
* @throws If the `apiKey` or `projectId` fields are missing in your
|
|
851
|
-
* Firebase config.
|
|
852
859
|
*
|
|
853
|
-
*
|
|
860
|
+
* Pros: callers needn't be concerned with details of on-device availability.</p>
|
|
861
|
+
* Cons: this method spans a few concerns and splits request validation from usage.
|
|
862
|
+
* If instance variables weren't already part of the API, we could consider a better
|
|
863
|
+
* separation of concerns.
|
|
854
864
|
*/
|
|
855
|
-
|
|
856
|
-
if (!
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
else if (!ai.app?.options?.projectId) {
|
|
860
|
-
throw new AIError(AIErrorCode.NO_PROJECT_ID, `The "projectId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid project ID.`);
|
|
865
|
+
async isAvailable(request) {
|
|
866
|
+
if (!this.mode) {
|
|
867
|
+
logger.debug(`On-device inference unavailable because mode is undefined.`);
|
|
868
|
+
return false;
|
|
861
869
|
}
|
|
862
|
-
|
|
863
|
-
|
|
870
|
+
if (this.mode === InferenceMode.ONLY_IN_CLOUD) {
|
|
871
|
+
logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
|
|
872
|
+
return false;
|
|
864
873
|
}
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
location: ai.location,
|
|
872
|
-
backend: ai.backend
|
|
873
|
-
};
|
|
874
|
-
if (_isFirebaseServerApp(ai.app) && ai.app.settings.appCheckToken) {
|
|
875
|
-
const token = ai.app.settings.appCheckToken;
|
|
876
|
-
this._apiSettings.getAppCheckToken = () => {
|
|
877
|
-
return Promise.resolve({ token });
|
|
878
|
-
};
|
|
874
|
+
// Triggers out-of-band download so model will eventually become available.
|
|
875
|
+
const availability = await this.downloadIfAvailable();
|
|
876
|
+
if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
|
|
877
|
+
// If it will never be available due to API inavailability, throw.
|
|
878
|
+
if (availability === Availability.UNAVAILABLE) {
|
|
879
|
+
throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
|
|
879
880
|
}
|
|
880
|
-
else if (
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
}
|
|
881
|
+
else if (availability === Availability.DOWNLOADABLE ||
|
|
882
|
+
availability === Availability.DOWNLOADING) {
|
|
883
|
+
// TODO(chholland): Better user experience during download - progress?
|
|
884
|
+
logger.debug(`Waiting for download of LanguageModel to complete.`);
|
|
885
|
+
await this.downloadPromise;
|
|
886
|
+
return true;
|
|
887
887
|
}
|
|
888
|
-
|
|
889
|
-
|
|
888
|
+
return true;
|
|
889
|
+
}
|
|
890
|
+
// Applies prefer_on_device logic.
|
|
891
|
+
if (availability !== Availability.AVAILABLE) {
|
|
892
|
+
logger.debug(`On-device inference unavailable because availability is "${availability}".`);
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
|
|
896
|
+
logger.debug(`On-device inference unavailable because request is incompatible.`);
|
|
897
|
+
return false;
|
|
898
|
+
}
|
|
899
|
+
return true;
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Generates content on device.
|
|
903
|
+
*
|
|
904
|
+
* @remarks
|
|
905
|
+
* This is comparable to {@link GenerativeModel.generateContent} for generating content in
|
|
906
|
+
* Cloud.
|
|
907
|
+
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
908
|
+
* @returns {@link Response}, so we can reuse common response formatting.
|
|
909
|
+
*/
|
|
910
|
+
async generateContent(request) {
|
|
911
|
+
const session = await this.createSession();
|
|
912
|
+
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
913
|
+
const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
|
|
914
|
+
return ChromeAdapterImpl.toResponse(text);
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Generates content stream on device.
|
|
918
|
+
*
|
|
919
|
+
* @remarks
|
|
920
|
+
* This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
|
|
921
|
+
* Cloud.
|
|
922
|
+
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
923
|
+
* @returns {@link Response}, so we can reuse common response formatting.
|
|
924
|
+
*/
|
|
925
|
+
async generateContentStream(request) {
|
|
926
|
+
const session = await this.createSession();
|
|
927
|
+
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
928
|
+
const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
|
|
929
|
+
return ChromeAdapterImpl.toStreamResponse(stream);
|
|
930
|
+
}
|
|
931
|
+
async countTokens(_request) {
|
|
932
|
+
throw new AIError(AIErrorCode.REQUEST_ERROR, 'Count Tokens is not yet available for on-device model.');
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Asserts inference for the given request can be performed by an on-device model.
|
|
936
|
+
*/
|
|
937
|
+
static isOnDeviceRequest(request) {
|
|
938
|
+
// Returns false if the prompt is empty.
|
|
939
|
+
if (request.contents.length === 0) {
|
|
940
|
+
logger.debug('Empty prompt rejected for on-device inference.');
|
|
941
|
+
return false;
|
|
942
|
+
}
|
|
943
|
+
for (const content of request.contents) {
|
|
944
|
+
if (content.role === 'function') {
|
|
945
|
+
logger.debug(`"Function" role rejected for on-device inference.`);
|
|
946
|
+
return false;
|
|
947
|
+
}
|
|
948
|
+
// Returns false if request contains an image with an unsupported mime type.
|
|
949
|
+
for (const part of content.parts) {
|
|
950
|
+
if (part.inlineData &&
|
|
951
|
+
ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
|
|
952
|
+
logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
|
|
953
|
+
return false;
|
|
954
|
+
}
|
|
890
955
|
}
|
|
891
|
-
this.model = AIModel.normalizeModelName(modelName, this._apiSettings.backend.backendType);
|
|
892
956
|
}
|
|
957
|
+
return true;
|
|
893
958
|
}
|
|
894
959
|
/**
|
|
895
|
-
*
|
|
960
|
+
* Encapsulates logic to get availability and download a model if one is downloadable.
|
|
961
|
+
*/
|
|
962
|
+
async downloadIfAvailable() {
|
|
963
|
+
const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
|
|
964
|
+
if (availability === Availability.DOWNLOADABLE) {
|
|
965
|
+
this.download();
|
|
966
|
+
}
|
|
967
|
+
return availability;
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* Triggers out-of-band download of an on-device model.
|
|
896
971
|
*
|
|
897
|
-
*
|
|
898
|
-
*
|
|
972
|
+
* Chrome only downloads models as needed. Chrome knows a model is needed when code calls
|
|
973
|
+
* LanguageModel.create.
|
|
899
974
|
*
|
|
900
|
-
*
|
|
975
|
+
* Since Chrome manages the download, the SDK can only avoid redundant download requests by
|
|
976
|
+
* tracking if a download has previously been requested.
|
|
901
977
|
*/
|
|
902
|
-
|
|
903
|
-
if (
|
|
904
|
-
return
|
|
978
|
+
download() {
|
|
979
|
+
if (this.isDownloading) {
|
|
980
|
+
return;
|
|
905
981
|
}
|
|
906
|
-
|
|
907
|
-
|
|
982
|
+
this.isDownloading = true;
|
|
983
|
+
this.downloadPromise = this.languageModelProvider
|
|
984
|
+
?.create(this.onDeviceParams.createOptions)
|
|
985
|
+
.finally(() => {
|
|
986
|
+
this.isDownloading = false;
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* Converts Firebase AI {@link Content} object to a Chrome {@link LanguageModelMessage} object.
|
|
991
|
+
*/
|
|
992
|
+
static async toLanguageModelMessage(content) {
|
|
993
|
+
const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
|
|
994
|
+
return {
|
|
995
|
+
role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
|
|
996
|
+
content: languageModelMessageContents
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Converts a Firebase AI Part object to a Chrome LanguageModelMessageContent object.
|
|
1001
|
+
*/
|
|
1002
|
+
static async toLanguageModelMessageContent(part) {
|
|
1003
|
+
if (part.text) {
|
|
1004
|
+
return {
|
|
1005
|
+
type: 'text',
|
|
1006
|
+
value: part.text
|
|
1007
|
+
};
|
|
908
1008
|
}
|
|
1009
|
+
else if (part.inlineData) {
|
|
1010
|
+
const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
|
|
1011
|
+
const imageBlob = await formattedImageContent.blob();
|
|
1012
|
+
const imageBitmap = await createImageBitmap(imageBlob);
|
|
1013
|
+
return {
|
|
1014
|
+
type: 'image',
|
|
1015
|
+
value: imageBitmap
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
|
|
909
1019
|
}
|
|
910
1020
|
/**
|
|
911
|
-
* @
|
|
1021
|
+
* Converts a Firebase AI {@link Role} string to a {@link LanguageModelMessageRole} string.
|
|
912
1022
|
*/
|
|
913
|
-
static
|
|
914
|
-
|
|
1023
|
+
static toLanguageModelMessageRole(role) {
|
|
1024
|
+
// Assumes 'function' rule has been filtered by isOnDeviceRequest
|
|
1025
|
+
return role === 'model' ? 'assistant' : 'user';
|
|
915
1026
|
}
|
|
916
1027
|
/**
|
|
917
|
-
*
|
|
1028
|
+
* Abstracts Chrome session creation.
|
|
1029
|
+
*
|
|
1030
|
+
* Chrome uses a multi-turn session for all inference. Firebase AI uses single-turn for all
|
|
1031
|
+
* inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
|
|
1032
|
+
* inference.
|
|
1033
|
+
*
|
|
1034
|
+
* Chrome will remove a model from memory if it's no longer in use, so this method ensures a
|
|
1035
|
+
* new session is created before an old session is destroyed.
|
|
918
1036
|
*/
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
if (modelName.startsWith('models/')) {
|
|
923
|
-
// Add 'publishers/google' if the user is only passing in 'models/model-name'.
|
|
924
|
-
model = `publishers/google/${modelName}`;
|
|
925
|
-
}
|
|
926
|
-
else {
|
|
927
|
-
// Any other custom format (e.g. tuned models) must be passed in correctly.
|
|
928
|
-
model = modelName;
|
|
929
|
-
}
|
|
1037
|
+
async createSession() {
|
|
1038
|
+
if (!this.languageModelProvider) {
|
|
1039
|
+
throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
|
|
930
1040
|
}
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
1041
|
+
const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
|
|
1042
|
+
if (this.oldSession) {
|
|
1043
|
+
this.oldSession.destroy();
|
|
934
1044
|
}
|
|
935
|
-
|
|
1045
|
+
// Holds session reference, so model isn't unloaded from memory.
|
|
1046
|
+
this.oldSession = newSession;
|
|
1047
|
+
return newSession;
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
|
|
1051
|
+
*/
|
|
1052
|
+
static toResponse(text) {
|
|
1053
|
+
return {
|
|
1054
|
+
json: async () => ({
|
|
1055
|
+
candidates: [
|
|
1056
|
+
{
|
|
1057
|
+
content: {
|
|
1058
|
+
parts: [{ text }]
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
]
|
|
1062
|
+
})
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Formats string stream returned by Chrome as SSE returned by Firebase AI.
|
|
1067
|
+
*/
|
|
1068
|
+
static toStreamResponse(stream) {
|
|
1069
|
+
const encoder = new TextEncoder();
|
|
1070
|
+
return {
|
|
1071
|
+
body: stream.pipeThrough(new TransformStream({
|
|
1072
|
+
transform(chunk, controller) {
|
|
1073
|
+
const json = JSON.stringify({
|
|
1074
|
+
candidates: [
|
|
1075
|
+
{
|
|
1076
|
+
content: {
|
|
1077
|
+
role: 'model',
|
|
1078
|
+
parts: [{ text: chunk }]
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
]
|
|
1082
|
+
});
|
|
1083
|
+
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
|
1084
|
+
}
|
|
1085
|
+
}))
|
|
1086
|
+
};
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
// Visible for testing
|
|
1090
|
+
ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
|
|
1091
|
+
/**
|
|
1092
|
+
* Creates a ChromeAdapterImpl on demand.
|
|
1093
|
+
*/
|
|
1094
|
+
function chromeAdapterFactory(mode, window, params) {
|
|
1095
|
+
// Do not initialize a ChromeAdapter if we are not in hybrid mode.
|
|
1096
|
+
if (typeof window !== 'undefined' && mode) {
|
|
1097
|
+
return new ChromeAdapterImpl(window.LanguageModel, mode, params);
|
|
936
1098
|
}
|
|
937
1099
|
}
|
|
938
1100
|
|
|
@@ -952,18 +1114,197 @@ class AIModel {
|
|
|
952
1114
|
* See the License for the specific language governing permissions and
|
|
953
1115
|
* limitations under the License.
|
|
954
1116
|
*/
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
1117
|
+
class AIService {
|
|
1118
|
+
constructor(app, backend, authProvider, appCheckProvider, chromeAdapterFactory) {
|
|
1119
|
+
this.app = app;
|
|
1120
|
+
this.backend = backend;
|
|
1121
|
+
this.chromeAdapterFactory = chromeAdapterFactory;
|
|
1122
|
+
const appCheck = appCheckProvider?.getImmediate({ optional: true });
|
|
1123
|
+
const auth = authProvider?.getImmediate({ optional: true });
|
|
1124
|
+
this.auth = auth || null;
|
|
1125
|
+
this.appCheck = appCheck || null;
|
|
1126
|
+
if (backend instanceof VertexAIBackend) {
|
|
1127
|
+
this.location = backend.location;
|
|
1128
|
+
}
|
|
1129
|
+
else {
|
|
1130
|
+
this.location = '';
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
_delete() {
|
|
1134
|
+
return Promise.resolve();
|
|
1135
|
+
}
|
|
1136
|
+
set options(optionsToSet) {
|
|
1137
|
+
this._options = optionsToSet;
|
|
1138
|
+
}
|
|
1139
|
+
get options() {
|
|
1140
|
+
return this._options;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
/**
|
|
1145
|
+
* @license
|
|
1146
|
+
* Copyright 2025 Google LLC
|
|
1147
|
+
*
|
|
1148
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1149
|
+
* you may not use this file except in compliance with the License.
|
|
1150
|
+
* You may obtain a copy of the License at
|
|
1151
|
+
*
|
|
1152
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1153
|
+
*
|
|
1154
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1155
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1156
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1157
|
+
* See the License for the specific language governing permissions and
|
|
1158
|
+
* limitations under the License.
|
|
1159
|
+
*/
|
|
1160
|
+
function factory(container, { instanceIdentifier }) {
|
|
1161
|
+
if (!instanceIdentifier) {
|
|
1162
|
+
throw new AIError(AIErrorCode.ERROR, 'AIService instance identifier is undefined.');
|
|
1163
|
+
}
|
|
1164
|
+
const backend = decodeInstanceIdentifier(instanceIdentifier);
|
|
1165
|
+
// getImmediate for FirebaseApp will always succeed
|
|
1166
|
+
const app = container.getProvider('app').getImmediate();
|
|
1167
|
+
const auth = container.getProvider('auth-internal');
|
|
1168
|
+
const appCheckProvider = container.getProvider('app-check-internal');
|
|
1169
|
+
return new AIService(app, backend, auth, appCheckProvider, chromeAdapterFactory);
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* @license
|
|
1174
|
+
* Copyright 2025 Google LLC
|
|
1175
|
+
*
|
|
1176
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1177
|
+
* you may not use this file except in compliance with the License.
|
|
1178
|
+
* You may obtain a copy of the License at
|
|
1179
|
+
*
|
|
1180
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1181
|
+
*
|
|
1182
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1183
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1184
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1185
|
+
* See the License for the specific language governing permissions and
|
|
1186
|
+
* limitations under the License.
|
|
1187
|
+
*/
|
|
1188
|
+
/**
|
|
1189
|
+
* Base class for Firebase AI model APIs.
|
|
1190
|
+
*
|
|
1191
|
+
* Instances of this class are associated with a specific Firebase AI {@link Backend}
|
|
1192
|
+
* and provide methods for interacting with the configured generative model.
|
|
1193
|
+
*
|
|
1194
|
+
* @public
|
|
1195
|
+
*/
|
|
1196
|
+
class AIModel {
|
|
1197
|
+
/**
|
|
1198
|
+
* Constructs a new instance of the {@link AIModel} class.
|
|
1199
|
+
*
|
|
1200
|
+
* This constructor should only be called from subclasses that provide
|
|
1201
|
+
* a model API.
|
|
1202
|
+
*
|
|
1203
|
+
* @param ai - an {@link AI} instance.
|
|
1204
|
+
* @param modelName - The name of the model being used. It can be in one of the following formats:
|
|
1205
|
+
* - `my-model` (short name, will resolve to `publishers/google/models/my-model`)
|
|
1206
|
+
* - `models/my-model` (will resolve to `publishers/google/models/my-model`)
|
|
1207
|
+
* - `publishers/my-publisher/models/my-model` (fully qualified model name)
|
|
1208
|
+
*
|
|
1209
|
+
* @throws If the `apiKey` or `projectId` fields are missing in your
|
|
1210
|
+
* Firebase config.
|
|
1211
|
+
*
|
|
1212
|
+
* @internal
|
|
1213
|
+
*/
|
|
1214
|
+
constructor(ai, modelName) {
|
|
1215
|
+
if (!ai.app?.options?.apiKey) {
|
|
1216
|
+
throw new AIError(AIErrorCode.NO_API_KEY, `The "apiKey" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid API key.`);
|
|
1217
|
+
}
|
|
1218
|
+
else if (!ai.app?.options?.projectId) {
|
|
1219
|
+
throw new AIError(AIErrorCode.NO_PROJECT_ID, `The "projectId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid project ID.`);
|
|
1220
|
+
}
|
|
1221
|
+
else if (!ai.app?.options?.appId) {
|
|
1222
|
+
throw new AIError(AIErrorCode.NO_APP_ID, `The "appId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid app ID.`);
|
|
1223
|
+
}
|
|
1224
|
+
else {
|
|
1225
|
+
this._apiSettings = {
|
|
1226
|
+
apiKey: ai.app.options.apiKey,
|
|
1227
|
+
project: ai.app.options.projectId,
|
|
1228
|
+
appId: ai.app.options.appId,
|
|
1229
|
+
automaticDataCollectionEnabled: ai.app.automaticDataCollectionEnabled,
|
|
1230
|
+
location: ai.location,
|
|
1231
|
+
backend: ai.backend
|
|
1232
|
+
};
|
|
1233
|
+
if (_isFirebaseServerApp(ai.app) && ai.app.settings.appCheckToken) {
|
|
1234
|
+
const token = ai.app.settings.appCheckToken;
|
|
1235
|
+
this._apiSettings.getAppCheckToken = () => {
|
|
1236
|
+
return Promise.resolve({ token });
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
else if (ai.appCheck) {
|
|
1240
|
+
if (ai.options?.useLimitedUseAppCheckTokens) {
|
|
1241
|
+
this._apiSettings.getAppCheckToken = () => ai.appCheck.getLimitedUseToken();
|
|
1242
|
+
}
|
|
1243
|
+
else {
|
|
1244
|
+
this._apiSettings.getAppCheckToken = () => ai.appCheck.getToken();
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
if (ai.auth) {
|
|
1248
|
+
this._apiSettings.getAuthToken = () => ai.auth.getToken();
|
|
1249
|
+
}
|
|
1250
|
+
this.model = AIModel.normalizeModelName(modelName, this._apiSettings.backend.backendType);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Normalizes the given model name to a fully qualified model resource name.
|
|
1255
|
+
*
|
|
1256
|
+
* @param modelName - The model name to normalize.
|
|
1257
|
+
* @returns The fully qualified model resource name.
|
|
1258
|
+
*
|
|
1259
|
+
* @internal
|
|
1260
|
+
*/
|
|
1261
|
+
static normalizeModelName(modelName, backendType) {
|
|
1262
|
+
if (backendType === BackendType.GOOGLE_AI) {
|
|
1263
|
+
return AIModel.normalizeGoogleAIModelName(modelName);
|
|
1264
|
+
}
|
|
1265
|
+
else {
|
|
1266
|
+
return AIModel.normalizeVertexAIModelName(modelName);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* @internal
|
|
1271
|
+
*/
|
|
1272
|
+
static normalizeGoogleAIModelName(modelName) {
|
|
1273
|
+
return `models/${modelName}`;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* @internal
|
|
1277
|
+
*/
|
|
1278
|
+
static normalizeVertexAIModelName(modelName) {
|
|
1279
|
+
let model;
|
|
1280
|
+
if (modelName.includes('/')) {
|
|
1281
|
+
if (modelName.startsWith('models/')) {
|
|
1282
|
+
// Add 'publishers/google' if the user is only passing in 'models/model-name'.
|
|
1283
|
+
model = `publishers/google/${modelName}`;
|
|
1284
|
+
}
|
|
1285
|
+
else {
|
|
1286
|
+
// Any other custom format (e.g. tuned models) must be passed in correctly.
|
|
1287
|
+
model = modelName;
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
else {
|
|
1291
|
+
// If path is not included, assume it's a non-tuned model.
|
|
1292
|
+
model = `publishers/google/models/${modelName}`;
|
|
1293
|
+
}
|
|
1294
|
+
return model;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
/**
|
|
1299
|
+
* @license
|
|
1300
|
+
* Copyright 2024 Google LLC
|
|
1301
|
+
*
|
|
1302
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1303
|
+
* you may not use this file except in compliance with the License.
|
|
1304
|
+
* You may obtain a copy of the License at
|
|
1305
|
+
*
|
|
1306
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1307
|
+
*
|
|
967
1308
|
* Unless required by applicable law or agreed to in writing, software
|
|
968
1309
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
969
1310
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
@@ -1734,6 +2075,72 @@ function aggregateResponses(responses) {
|
|
|
1734
2075
|
return aggregatedResponse;
|
|
1735
2076
|
}
|
|
1736
2077
|
|
|
2078
|
+
/**
|
|
2079
|
+
* @license
|
|
2080
|
+
* Copyright 2025 Google LLC
|
|
2081
|
+
*
|
|
2082
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2083
|
+
* you may not use this file except in compliance with the License.
|
|
2084
|
+
* You may obtain a copy of the License at
|
|
2085
|
+
*
|
|
2086
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2087
|
+
*
|
|
2088
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2089
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2090
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2091
|
+
* See the License for the specific language governing permissions and
|
|
2092
|
+
* limitations under the License.
|
|
2093
|
+
*/
|
|
2094
|
+
const errorsCausingFallback = [
|
|
2095
|
+
// most network errors
|
|
2096
|
+
AIErrorCode.FETCH_ERROR,
|
|
2097
|
+
// fallback code for all other errors in makeRequest
|
|
2098
|
+
AIErrorCode.ERROR,
|
|
2099
|
+
// error due to API not being enabled in project
|
|
2100
|
+
AIErrorCode.API_NOT_ENABLED
|
|
2101
|
+
];
|
|
2102
|
+
/**
|
|
2103
|
+
* Dispatches a request to the appropriate backend (on-device or in-cloud)
|
|
2104
|
+
* based on the inference mode.
|
|
2105
|
+
*
|
|
2106
|
+
* @param request - The request to be sent.
|
|
2107
|
+
* @param chromeAdapter - The on-device model adapter.
|
|
2108
|
+
* @param onDeviceCall - The function to call for on-device inference.
|
|
2109
|
+
* @param inCloudCall - The function to call for in-cloud inference.
|
|
2110
|
+
* @returns The response from the backend.
|
|
2111
|
+
*/
|
|
2112
|
+
async function callCloudOrDevice(request, chromeAdapter, onDeviceCall, inCloudCall) {
|
|
2113
|
+
if (!chromeAdapter) {
|
|
2114
|
+
return inCloudCall();
|
|
2115
|
+
}
|
|
2116
|
+
switch (chromeAdapter.mode) {
|
|
2117
|
+
case InferenceMode.ONLY_ON_DEVICE:
|
|
2118
|
+
if (await chromeAdapter.isAvailable(request)) {
|
|
2119
|
+
return onDeviceCall();
|
|
2120
|
+
}
|
|
2121
|
+
throw new AIError(AIErrorCode.UNSUPPORTED, 'Inference mode is ONLY_ON_DEVICE, but an on-device model is not available.');
|
|
2122
|
+
case InferenceMode.ONLY_IN_CLOUD:
|
|
2123
|
+
return inCloudCall();
|
|
2124
|
+
case InferenceMode.PREFER_IN_CLOUD:
|
|
2125
|
+
try {
|
|
2126
|
+
return await inCloudCall();
|
|
2127
|
+
}
|
|
2128
|
+
catch (e) {
|
|
2129
|
+
if (e instanceof AIError && errorsCausingFallback.includes(e.code)) {
|
|
2130
|
+
return onDeviceCall();
|
|
2131
|
+
}
|
|
2132
|
+
throw e;
|
|
2133
|
+
}
|
|
2134
|
+
case InferenceMode.PREFER_ON_DEVICE:
|
|
2135
|
+
if (await chromeAdapter.isAvailable(request)) {
|
|
2136
|
+
return onDeviceCall();
|
|
2137
|
+
}
|
|
2138
|
+
return inCloudCall();
|
|
2139
|
+
default:
|
|
2140
|
+
throw new AIError(AIErrorCode.ERROR, `Unexpected infererence mode: ${chromeAdapter.mode}`);
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
|
|
1737
2144
|
/**
|
|
1738
2145
|
* @license
|
|
1739
2146
|
* Copyright 2024 Google LLC
|
|
@@ -1758,13 +2165,7 @@ async function generateContentStreamOnCloud(apiSettings, model, params, requestO
|
|
|
1758
2165
|
/* stream */ true, JSON.stringify(params), requestOptions);
|
|
1759
2166
|
}
|
|
1760
2167
|
async function generateContentStream(apiSettings, model, params, chromeAdapter, requestOptions) {
|
|
1761
|
-
|
|
1762
|
-
if (chromeAdapter && (await chromeAdapter.isAvailable(params))) {
|
|
1763
|
-
response = await chromeAdapter.generateContentStream(params);
|
|
1764
|
-
}
|
|
1765
|
-
else {
|
|
1766
|
-
response = await generateContentStreamOnCloud(apiSettings, model, params, requestOptions);
|
|
1767
|
-
}
|
|
2168
|
+
const response = await callCloudOrDevice(params, chromeAdapter, () => chromeAdapter.generateContentStream(params), () => generateContentStreamOnCloud(apiSettings, model, params, requestOptions));
|
|
1768
2169
|
return processStream(response, apiSettings); // TODO: Map streaming responses
|
|
1769
2170
|
}
|
|
1770
2171
|
async function generateContentOnCloud(apiSettings, model, params, requestOptions) {
|
|
@@ -1775,13 +2176,7 @@ async function generateContentOnCloud(apiSettings, model, params, requestOptions
|
|
|
1775
2176
|
/* stream */ false, JSON.stringify(params), requestOptions);
|
|
1776
2177
|
}
|
|
1777
2178
|
async function generateContent(apiSettings, model, params, chromeAdapter, requestOptions) {
|
|
1778
|
-
|
|
1779
|
-
if (chromeAdapter && (await chromeAdapter.isAvailable(params))) {
|
|
1780
|
-
response = await chromeAdapter.generateContent(params);
|
|
1781
|
-
}
|
|
1782
|
-
else {
|
|
1783
|
-
response = await generateContentOnCloud(apiSettings, model, params, requestOptions);
|
|
1784
|
-
}
|
|
2179
|
+
const response = await callCloudOrDevice(params, chromeAdapter, () => chromeAdapter.generateContent(params), () => generateContentOnCloud(apiSettings, model, params, requestOptions));
|
|
1785
2180
|
const generateContentResponse = await processGenerateContentResponse(response, apiSettings);
|
|
1786
2181
|
const enhancedResponse = createEnhancedContentResponse(generateContentResponse);
|
|
1787
2182
|
return {
|
|
@@ -2192,8 +2587,8 @@ async function countTokensOnCloud(apiSettings, model, params, requestOptions) {
|
|
|
2192
2587
|
return response.json();
|
|
2193
2588
|
}
|
|
2194
2589
|
async function countTokens(apiSettings, model, params, chromeAdapter, requestOptions) {
|
|
2195
|
-
if (chromeAdapter
|
|
2196
|
-
|
|
2590
|
+
if (chromeAdapter?.mode === InferenceMode.ONLY_ON_DEVICE) {
|
|
2591
|
+
throw new AIError(AIErrorCode.UNSUPPORTED, 'countTokens() is not supported for on-device models.');
|
|
2197
2592
|
}
|
|
2198
2593
|
return countTokensOnCloud(apiSettings, model, params, requestOptions);
|
|
2199
2594
|
}
|
|
@@ -3607,316 +4002,10 @@ function getLiveGenerativeModel(ai, modelParams) {
|
|
|
3607
4002
|
}
|
|
3608
4003
|
|
|
3609
4004
|
/**
|
|
3610
|
-
*
|
|
3611
|
-
*/
|
|
3612
|
-
var Availability;
|
|
3613
|
-
(function (Availability) {
|
|
3614
|
-
Availability["UNAVAILABLE"] = "unavailable";
|
|
3615
|
-
Availability["DOWNLOADABLE"] = "downloadable";
|
|
3616
|
-
Availability["DOWNLOADING"] = "downloading";
|
|
3617
|
-
Availability["AVAILABLE"] = "available";
|
|
3618
|
-
})(Availability || (Availability = {}));
|
|
3619
|
-
|
|
3620
|
-
/**
|
|
3621
|
-
* @license
|
|
3622
|
-
* Copyright 2025 Google LLC
|
|
3623
|
-
*
|
|
3624
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
3625
|
-
* you may not use this file except in compliance with the License.
|
|
3626
|
-
* You may obtain a copy of the License at
|
|
3627
|
-
*
|
|
3628
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
3629
|
-
*
|
|
3630
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
3631
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
3632
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
3633
|
-
* See the License for the specific language governing permissions and
|
|
3634
|
-
* limitations under the License.
|
|
3635
|
-
*/
|
|
3636
|
-
/**
|
|
3637
|
-
* Defines an inference "backend" that uses Chrome's on-device model,
|
|
3638
|
-
* and encapsulates logic for detecting when on-device inference is
|
|
3639
|
-
* possible.
|
|
3640
|
-
*/
|
|
3641
|
-
class ChromeAdapterImpl {
|
|
3642
|
-
constructor(languageModelProvider, mode, onDeviceParams = {
|
|
3643
|
-
createOptions: {
|
|
3644
|
-
// Defaults to support image inputs for convenience.
|
|
3645
|
-
expectedInputs: [{ type: 'image' }]
|
|
3646
|
-
}
|
|
3647
|
-
}) {
|
|
3648
|
-
this.languageModelProvider = languageModelProvider;
|
|
3649
|
-
this.mode = mode;
|
|
3650
|
-
this.onDeviceParams = onDeviceParams;
|
|
3651
|
-
this.isDownloading = false;
|
|
3652
|
-
}
|
|
3653
|
-
/**
|
|
3654
|
-
* Checks if a given request can be made on-device.
|
|
3655
|
-
*
|
|
3656
|
-
* Encapsulates a few concerns:
|
|
3657
|
-
* the mode
|
|
3658
|
-
* API existence
|
|
3659
|
-
* prompt formatting
|
|
3660
|
-
* model availability, including triggering download if necessary
|
|
3661
|
-
*
|
|
3662
|
-
*
|
|
3663
|
-
* Pros: callers needn't be concerned with details of on-device availability.</p>
|
|
3664
|
-
* Cons: this method spans a few concerns and splits request validation from usage.
|
|
3665
|
-
* If instance variables weren't already part of the API, we could consider a better
|
|
3666
|
-
* separation of concerns.
|
|
3667
|
-
*/
|
|
3668
|
-
async isAvailable(request) {
|
|
3669
|
-
if (!this.mode) {
|
|
3670
|
-
logger.debug(`On-device inference unavailable because mode is undefined.`);
|
|
3671
|
-
return false;
|
|
3672
|
-
}
|
|
3673
|
-
if (this.mode === InferenceMode.ONLY_IN_CLOUD) {
|
|
3674
|
-
logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
|
|
3675
|
-
return false;
|
|
3676
|
-
}
|
|
3677
|
-
// Triggers out-of-band download so model will eventually become available.
|
|
3678
|
-
const availability = await this.downloadIfAvailable();
|
|
3679
|
-
if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
|
|
3680
|
-
// If it will never be available due to API inavailability, throw.
|
|
3681
|
-
if (availability === Availability.UNAVAILABLE) {
|
|
3682
|
-
throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
|
|
3683
|
-
}
|
|
3684
|
-
else if (availability === Availability.DOWNLOADABLE ||
|
|
3685
|
-
availability === Availability.DOWNLOADING) {
|
|
3686
|
-
// TODO(chholland): Better user experience during download - progress?
|
|
3687
|
-
logger.debug(`Waiting for download of LanguageModel to complete.`);
|
|
3688
|
-
await this.downloadPromise;
|
|
3689
|
-
return true;
|
|
3690
|
-
}
|
|
3691
|
-
return true;
|
|
3692
|
-
}
|
|
3693
|
-
// Applies prefer_on_device logic.
|
|
3694
|
-
if (availability !== Availability.AVAILABLE) {
|
|
3695
|
-
logger.debug(`On-device inference unavailable because availability is "${availability}".`);
|
|
3696
|
-
return false;
|
|
3697
|
-
}
|
|
3698
|
-
if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
|
|
3699
|
-
logger.debug(`On-device inference unavailable because request is incompatible.`);
|
|
3700
|
-
return false;
|
|
3701
|
-
}
|
|
3702
|
-
return true;
|
|
3703
|
-
}
|
|
3704
|
-
/**
|
|
3705
|
-
* Generates content on device.
|
|
3706
|
-
*
|
|
3707
|
-
* @remarks
|
|
3708
|
-
* This is comparable to {@link GenerativeModel.generateContent} for generating content in
|
|
3709
|
-
* Cloud.
|
|
3710
|
-
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
3711
|
-
* @returns {@link Response}, so we can reuse common response formatting.
|
|
3712
|
-
*/
|
|
3713
|
-
async generateContent(request) {
|
|
3714
|
-
const session = await this.createSession();
|
|
3715
|
-
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
3716
|
-
const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
|
|
3717
|
-
return ChromeAdapterImpl.toResponse(text);
|
|
3718
|
-
}
|
|
3719
|
-
/**
|
|
3720
|
-
* Generates content stream on device.
|
|
3721
|
-
*
|
|
3722
|
-
* @remarks
|
|
3723
|
-
* This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
|
|
3724
|
-
* Cloud.
|
|
3725
|
-
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
3726
|
-
* @returns {@link Response}, so we can reuse common response formatting.
|
|
3727
|
-
*/
|
|
3728
|
-
async generateContentStream(request) {
|
|
3729
|
-
const session = await this.createSession();
|
|
3730
|
-
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
3731
|
-
const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
|
|
3732
|
-
return ChromeAdapterImpl.toStreamResponse(stream);
|
|
3733
|
-
}
|
|
3734
|
-
async countTokens(_request) {
|
|
3735
|
-
throw new AIError(AIErrorCode.REQUEST_ERROR, 'Count Tokens is not yet available for on-device model.');
|
|
3736
|
-
}
|
|
3737
|
-
/**
|
|
3738
|
-
* Asserts inference for the given request can be performed by an on-device model.
|
|
3739
|
-
*/
|
|
3740
|
-
static isOnDeviceRequest(request) {
|
|
3741
|
-
// Returns false if the prompt is empty.
|
|
3742
|
-
if (request.contents.length === 0) {
|
|
3743
|
-
logger.debug('Empty prompt rejected for on-device inference.');
|
|
3744
|
-
return false;
|
|
3745
|
-
}
|
|
3746
|
-
for (const content of request.contents) {
|
|
3747
|
-
if (content.role === 'function') {
|
|
3748
|
-
logger.debug(`"Function" role rejected for on-device inference.`);
|
|
3749
|
-
return false;
|
|
3750
|
-
}
|
|
3751
|
-
// Returns false if request contains an image with an unsupported mime type.
|
|
3752
|
-
for (const part of content.parts) {
|
|
3753
|
-
if (part.inlineData &&
|
|
3754
|
-
ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
|
|
3755
|
-
logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
|
|
3756
|
-
return false;
|
|
3757
|
-
}
|
|
3758
|
-
}
|
|
3759
|
-
}
|
|
3760
|
-
return true;
|
|
3761
|
-
}
|
|
3762
|
-
/**
|
|
3763
|
-
* Encapsulates logic to get availability and download a model if one is downloadable.
|
|
3764
|
-
*/
|
|
3765
|
-
async downloadIfAvailable() {
|
|
3766
|
-
const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
|
|
3767
|
-
if (availability === Availability.DOWNLOADABLE) {
|
|
3768
|
-
this.download();
|
|
3769
|
-
}
|
|
3770
|
-
return availability;
|
|
3771
|
-
}
|
|
3772
|
-
/**
|
|
3773
|
-
* Triggers out-of-band download of an on-device model.
|
|
3774
|
-
*
|
|
3775
|
-
* Chrome only downloads models as needed. Chrome knows a model is needed when code calls
|
|
3776
|
-
* LanguageModel.create.
|
|
3777
|
-
*
|
|
3778
|
-
* Since Chrome manages the download, the SDK can only avoid redundant download requests by
|
|
3779
|
-
* tracking if a download has previously been requested.
|
|
3780
|
-
*/
|
|
3781
|
-
download() {
|
|
3782
|
-
if (this.isDownloading) {
|
|
3783
|
-
return;
|
|
3784
|
-
}
|
|
3785
|
-
this.isDownloading = true;
|
|
3786
|
-
this.downloadPromise = this.languageModelProvider
|
|
3787
|
-
?.create(this.onDeviceParams.createOptions)
|
|
3788
|
-
.finally(() => {
|
|
3789
|
-
this.isDownloading = false;
|
|
3790
|
-
});
|
|
3791
|
-
}
|
|
3792
|
-
/**
|
|
3793
|
-
* Converts Firebase AI {@link Content} object to a Chrome {@link LanguageModelMessage} object.
|
|
3794
|
-
*/
|
|
3795
|
-
static async toLanguageModelMessage(content) {
|
|
3796
|
-
const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
|
|
3797
|
-
return {
|
|
3798
|
-
role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
|
|
3799
|
-
content: languageModelMessageContents
|
|
3800
|
-
};
|
|
3801
|
-
}
|
|
3802
|
-
/**
|
|
3803
|
-
* Converts a Firebase AI Part object to a Chrome LanguageModelMessageContent object.
|
|
3804
|
-
*/
|
|
3805
|
-
static async toLanguageModelMessageContent(part) {
|
|
3806
|
-
if (part.text) {
|
|
3807
|
-
return {
|
|
3808
|
-
type: 'text',
|
|
3809
|
-
value: part.text
|
|
3810
|
-
};
|
|
3811
|
-
}
|
|
3812
|
-
else if (part.inlineData) {
|
|
3813
|
-
const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
|
|
3814
|
-
const imageBlob = await formattedImageContent.blob();
|
|
3815
|
-
const imageBitmap = await createImageBitmap(imageBlob);
|
|
3816
|
-
return {
|
|
3817
|
-
type: 'image',
|
|
3818
|
-
value: imageBitmap
|
|
3819
|
-
};
|
|
3820
|
-
}
|
|
3821
|
-
throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
|
|
3822
|
-
}
|
|
3823
|
-
/**
|
|
3824
|
-
* Converts a Firebase AI {@link Role} string to a {@link LanguageModelMessageRole} string.
|
|
3825
|
-
*/
|
|
3826
|
-
static toLanguageModelMessageRole(role) {
|
|
3827
|
-
// Assumes 'function' rule has been filtered by isOnDeviceRequest
|
|
3828
|
-
return role === 'model' ? 'assistant' : 'user';
|
|
3829
|
-
}
|
|
3830
|
-
/**
|
|
3831
|
-
* Abstracts Chrome session creation.
|
|
3832
|
-
*
|
|
3833
|
-
* Chrome uses a multi-turn session for all inference. Firebase AI uses single-turn for all
|
|
3834
|
-
* inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
|
|
3835
|
-
* inference.
|
|
3836
|
-
*
|
|
3837
|
-
* Chrome will remove a model from memory if it's no longer in use, so this method ensures a
|
|
3838
|
-
* new session is created before an old session is destroyed.
|
|
3839
|
-
*/
|
|
3840
|
-
async createSession() {
|
|
3841
|
-
if (!this.languageModelProvider) {
|
|
3842
|
-
throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
|
|
3843
|
-
}
|
|
3844
|
-
const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
|
|
3845
|
-
if (this.oldSession) {
|
|
3846
|
-
this.oldSession.destroy();
|
|
3847
|
-
}
|
|
3848
|
-
// Holds session reference, so model isn't unloaded from memory.
|
|
3849
|
-
this.oldSession = newSession;
|
|
3850
|
-
return newSession;
|
|
3851
|
-
}
|
|
3852
|
-
/**
|
|
3853
|
-
* Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
|
|
3854
|
-
*/
|
|
3855
|
-
static toResponse(text) {
|
|
3856
|
-
return {
|
|
3857
|
-
json: async () => ({
|
|
3858
|
-
candidates: [
|
|
3859
|
-
{
|
|
3860
|
-
content: {
|
|
3861
|
-
parts: [{ text }]
|
|
3862
|
-
}
|
|
3863
|
-
}
|
|
3864
|
-
]
|
|
3865
|
-
})
|
|
3866
|
-
};
|
|
3867
|
-
}
|
|
3868
|
-
/**
|
|
3869
|
-
* Formats string stream returned by Chrome as SSE returned by Firebase AI.
|
|
3870
|
-
*/
|
|
3871
|
-
static toStreamResponse(stream) {
|
|
3872
|
-
const encoder = new TextEncoder();
|
|
3873
|
-
return {
|
|
3874
|
-
body: stream.pipeThrough(new TransformStream({
|
|
3875
|
-
transform(chunk, controller) {
|
|
3876
|
-
const json = JSON.stringify({
|
|
3877
|
-
candidates: [
|
|
3878
|
-
{
|
|
3879
|
-
content: {
|
|
3880
|
-
role: 'model',
|
|
3881
|
-
parts: [{ text: chunk }]
|
|
3882
|
-
}
|
|
3883
|
-
}
|
|
3884
|
-
]
|
|
3885
|
-
});
|
|
3886
|
-
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
|
3887
|
-
}
|
|
3888
|
-
}))
|
|
3889
|
-
};
|
|
3890
|
-
}
|
|
3891
|
-
}
|
|
3892
|
-
// Visible for testing
|
|
3893
|
-
ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
|
|
3894
|
-
/**
|
|
3895
|
-
* Creates a ChromeAdapterImpl on demand.
|
|
3896
|
-
*/
|
|
3897
|
-
function chromeAdapterFactory(mode, window, params) {
|
|
3898
|
-
// Do not initialize a ChromeAdapter if we are not in hybrid mode.
|
|
3899
|
-
if (typeof window !== 'undefined' && mode) {
|
|
3900
|
-
return new ChromeAdapterImpl(window.LanguageModel, mode, params);
|
|
3901
|
-
}
|
|
3902
|
-
}
|
|
3903
|
-
|
|
3904
|
-
/**
|
|
3905
|
-
* The Firebase AI Web SDK.
|
|
4005
|
+
* The Firebase AI Web SDK.
|
|
3906
4006
|
*
|
|
3907
4007
|
* @packageDocumentation
|
|
3908
4008
|
*/
|
|
3909
|
-
function factory(container, { instanceIdentifier }) {
|
|
3910
|
-
if (!instanceIdentifier) {
|
|
3911
|
-
throw new AIError(AIErrorCode.ERROR, 'AIService instance identifier is undefined.');
|
|
3912
|
-
}
|
|
3913
|
-
const backend = decodeInstanceIdentifier(instanceIdentifier);
|
|
3914
|
-
// getImmediate for FirebaseApp will always succeed
|
|
3915
|
-
const app = container.getProvider('app').getImmediate();
|
|
3916
|
-
const auth = container.getProvider('auth-internal');
|
|
3917
|
-
const appCheckProvider = container.getProvider('app-check-internal');
|
|
3918
|
-
return new AIService(app, backend, auth, appCheckProvider, chromeAdapterFactory);
|
|
3919
|
-
}
|
|
3920
4009
|
function registerAI() {
|
|
3921
4010
|
_registerComponent(new Component(AI_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
|
|
3922
4011
|
registerVersion(name, version);
|
|
@@ -3925,5 +4014,5 @@ function registerAI() {
|
|
|
3925
4014
|
}
|
|
3926
4015
|
registerAI();
|
|
3927
4016
|
|
|
3928
|
-
export { AIError, AIErrorCode, AIModel, AnyOfSchema, ArraySchema, Backend, BackendType, BlockReason, BooleanSchema, ChatSession, FinishReason, FunctionCallingMode, GenerativeModel, GoogleAIBackend, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, ImagenAspectRatio, ImagenImageFormat, ImagenModel, ImagenPersonFilterLevel, ImagenSafetyFilterLevel, InferenceMode, IntegerSchema, LiveGenerativeModel, LiveResponseType, LiveSession, Modality, NumberSchema, ObjectSchema, POSSIBLE_ROLES, ResponseModality, Schema, SchemaType, StringSchema, VertexAIBackend,
|
|
4017
|
+
export { AIError, AIErrorCode, AIModel, AnyOfSchema, ArraySchema, Backend, BackendType, BlockReason, BooleanSchema, ChatSession, FinishReason, FunctionCallingMode, GenerativeModel, GoogleAIBackend, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, ImagenAspectRatio, ImagenImageFormat, ImagenModel, ImagenPersonFilterLevel, ImagenSafetyFilterLevel, InferenceMode, IntegerSchema, LiveGenerativeModel, LiveResponseType, LiveSession, Modality, NumberSchema, ObjectSchema, POSSIBLE_ROLES, ResponseModality, Schema, SchemaType, StringSchema, VertexAIBackend, getAI, getGenerativeModel, getImagenModel, getLiveGenerativeModel, startAudioConversation };
|
|
3929
4018
|
//# sourceMappingURL=index.esm.js.map
|