@firebase/ai 2.2.1-canary.4d834deb2 → 2.2.1-canary.55f3f83a7
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/esm/index.esm.js +518 -501
- package/dist/esm/index.esm.js.map +1 -1
- package/dist/esm/src/factory-browser.d.ts +19 -0
- package/dist/index.cjs.js +518 -501
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.node.cjs.js +1 -1
- package/dist/index.node.mjs +1 -1
- package/dist/src/factory-browser.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.1-canary.
|
|
7
|
+
var version = "2.2.1-canary.55f3f83a7";
|
|
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
|
|
@@ -653,105 +709,6 @@ class VertexAIBackend extends Backend {
|
|
|
653
709
|
}
|
|
654
710
|
}
|
|
655
711
|
|
|
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
712
|
/**
|
|
756
713
|
* @license
|
|
757
714
|
* Copyright 2025 Google LLC
|
|
@@ -812,7 +769,7 @@ function decodeInstanceIdentifier(instanceIdentifier) {
|
|
|
812
769
|
|
|
813
770
|
/**
|
|
814
771
|
* @license
|
|
815
|
-
* Copyright
|
|
772
|
+
* Copyright 2024 Google LLC
|
|
816
773
|
*
|
|
817
774
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
818
775
|
* you may not use this file except in compliance with the License.
|
|
@@ -826,133 +783,302 @@ function decodeInstanceIdentifier(instanceIdentifier) {
|
|
|
826
783
|
* See the License for the specific language governing permissions and
|
|
827
784
|
* limitations under the License.
|
|
828
785
|
*/
|
|
786
|
+
const logger = new Logger('@firebase/vertexai');
|
|
787
|
+
|
|
829
788
|
/**
|
|
830
|
-
*
|
|
789
|
+
* @internal
|
|
790
|
+
*/
|
|
791
|
+
var Availability;
|
|
792
|
+
(function (Availability) {
|
|
793
|
+
Availability["UNAVAILABLE"] = "unavailable";
|
|
794
|
+
Availability["DOWNLOADABLE"] = "downloadable";
|
|
795
|
+
Availability["DOWNLOADING"] = "downloading";
|
|
796
|
+
Availability["AVAILABLE"] = "available";
|
|
797
|
+
})(Availability || (Availability = {}));
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* @license
|
|
801
|
+
* Copyright 2025 Google LLC
|
|
831
802
|
*
|
|
832
|
-
*
|
|
833
|
-
*
|
|
803
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
804
|
+
* you may not use this file except in compliance with the License.
|
|
805
|
+
* You may obtain a copy of the License at
|
|
834
806
|
*
|
|
835
|
-
*
|
|
807
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
808
|
+
*
|
|
809
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
810
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
811
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
812
|
+
* See the License for the specific language governing permissions and
|
|
813
|
+
* limitations under the License.
|
|
836
814
|
*/
|
|
837
|
-
|
|
815
|
+
/**
|
|
816
|
+
* Defines an inference "backend" that uses Chrome's on-device model,
|
|
817
|
+
* and encapsulates logic for detecting when on-device inference is
|
|
818
|
+
* possible.
|
|
819
|
+
*/
|
|
820
|
+
class ChromeAdapterImpl {
|
|
821
|
+
constructor(languageModelProvider, mode, onDeviceParams = {
|
|
822
|
+
createOptions: {
|
|
823
|
+
// Defaults to support image inputs for convenience.
|
|
824
|
+
expectedInputs: [{ type: 'image' }]
|
|
825
|
+
}
|
|
826
|
+
}) {
|
|
827
|
+
this.languageModelProvider = languageModelProvider;
|
|
828
|
+
this.mode = mode;
|
|
829
|
+
this.onDeviceParams = onDeviceParams;
|
|
830
|
+
this.isDownloading = false;
|
|
831
|
+
}
|
|
838
832
|
/**
|
|
839
|
-
*
|
|
840
|
-
*
|
|
841
|
-
* This constructor should only be called from subclasses that provide
|
|
842
|
-
* a model API.
|
|
833
|
+
* Checks if a given request can be made on-device.
|
|
843
834
|
*
|
|
844
|
-
*
|
|
845
|
-
*
|
|
846
|
-
*
|
|
847
|
-
*
|
|
848
|
-
*
|
|
835
|
+
* Encapsulates a few concerns:
|
|
836
|
+
* the mode
|
|
837
|
+
* API existence
|
|
838
|
+
* prompt formatting
|
|
839
|
+
* model availability, including triggering download if necessary
|
|
849
840
|
*
|
|
850
|
-
* @throws If the `apiKey` or `projectId` fields are missing in your
|
|
851
|
-
* Firebase config.
|
|
852
841
|
*
|
|
853
|
-
*
|
|
842
|
+
* Pros: callers needn't be concerned with details of on-device availability.</p>
|
|
843
|
+
* Cons: this method spans a few concerns and splits request validation from usage.
|
|
844
|
+
* If instance variables weren't already part of the API, we could consider a better
|
|
845
|
+
* separation of concerns.
|
|
854
846
|
*/
|
|
855
|
-
|
|
856
|
-
if (!
|
|
857
|
-
|
|
847
|
+
async isAvailable(request) {
|
|
848
|
+
if (!this.mode) {
|
|
849
|
+
logger.debug(`On-device inference unavailable because mode is undefined.`);
|
|
850
|
+
return false;
|
|
858
851
|
}
|
|
859
|
-
|
|
860
|
-
|
|
852
|
+
if (this.mode === InferenceMode.ONLY_IN_CLOUD) {
|
|
853
|
+
logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
|
|
854
|
+
return false;
|
|
861
855
|
}
|
|
862
|
-
|
|
863
|
-
|
|
856
|
+
// Triggers out-of-band download so model will eventually become available.
|
|
857
|
+
const availability = await this.downloadIfAvailable();
|
|
858
|
+
if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
|
|
859
|
+
// If it will never be available due to API inavailability, throw.
|
|
860
|
+
if (availability === Availability.UNAVAILABLE) {
|
|
861
|
+
throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
|
|
862
|
+
}
|
|
863
|
+
else if (availability === Availability.DOWNLOADABLE ||
|
|
864
|
+
availability === Availability.DOWNLOADING) {
|
|
865
|
+
// TODO(chholland): Better user experience during download - progress?
|
|
866
|
+
logger.debug(`Waiting for download of LanguageModel to complete.`);
|
|
867
|
+
await this.downloadPromise;
|
|
868
|
+
return true;
|
|
869
|
+
}
|
|
870
|
+
return true;
|
|
864
871
|
}
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
872
|
+
// Applies prefer_on_device logic.
|
|
873
|
+
if (availability !== Availability.AVAILABLE) {
|
|
874
|
+
logger.debug(`On-device inference unavailable because availability is "${availability}".`);
|
|
875
|
+
return false;
|
|
876
|
+
}
|
|
877
|
+
if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
|
|
878
|
+
logger.debug(`On-device inference unavailable because request is incompatible.`);
|
|
879
|
+
return false;
|
|
880
|
+
}
|
|
881
|
+
return true;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Generates content on device.
|
|
885
|
+
*
|
|
886
|
+
* @remarks
|
|
887
|
+
* This is comparable to {@link GenerativeModel.generateContent} for generating content in
|
|
888
|
+
* Cloud.
|
|
889
|
+
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
890
|
+
* @returns {@link Response}, so we can reuse common response formatting.
|
|
891
|
+
*/
|
|
892
|
+
async generateContent(request) {
|
|
893
|
+
const session = await this.createSession();
|
|
894
|
+
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
895
|
+
const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
|
|
896
|
+
return ChromeAdapterImpl.toResponse(text);
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Generates content stream on device.
|
|
900
|
+
*
|
|
901
|
+
* @remarks
|
|
902
|
+
* This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
|
|
903
|
+
* Cloud.
|
|
904
|
+
* @param request - a standard Firebase AI {@link GenerateContentRequest}
|
|
905
|
+
* @returns {@link Response}, so we can reuse common response formatting.
|
|
906
|
+
*/
|
|
907
|
+
async generateContentStream(request) {
|
|
908
|
+
const session = await this.createSession();
|
|
909
|
+
const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
|
|
910
|
+
const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
|
|
911
|
+
return ChromeAdapterImpl.toStreamResponse(stream);
|
|
912
|
+
}
|
|
913
|
+
async countTokens(_request) {
|
|
914
|
+
throw new AIError(AIErrorCode.REQUEST_ERROR, 'Count Tokens is not yet available for on-device model.');
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Asserts inference for the given request can be performed by an on-device model.
|
|
918
|
+
*/
|
|
919
|
+
static isOnDeviceRequest(request) {
|
|
920
|
+
// Returns false if the prompt is empty.
|
|
921
|
+
if (request.contents.length === 0) {
|
|
922
|
+
logger.debug('Empty prompt rejected for on-device inference.');
|
|
923
|
+
return false;
|
|
924
|
+
}
|
|
925
|
+
for (const content of request.contents) {
|
|
926
|
+
if (content.role === 'function') {
|
|
927
|
+
logger.debug(`"Function" role rejected for on-device inference.`);
|
|
928
|
+
return false;
|
|
879
929
|
}
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
930
|
+
// Returns false if request contains an image with an unsupported mime type.
|
|
931
|
+
for (const part of content.parts) {
|
|
932
|
+
if (part.inlineData &&
|
|
933
|
+
ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
|
|
934
|
+
logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
|
|
935
|
+
return false;
|
|
886
936
|
}
|
|
887
937
|
}
|
|
888
|
-
if (ai.auth) {
|
|
889
|
-
this._apiSettings.getAuthToken = () => ai.auth.getToken();
|
|
890
|
-
}
|
|
891
|
-
this.model = AIModel.normalizeModelName(modelName, this._apiSettings.backend.backendType);
|
|
892
938
|
}
|
|
939
|
+
return true;
|
|
893
940
|
}
|
|
894
941
|
/**
|
|
895
|
-
*
|
|
942
|
+
* Encapsulates logic to get availability and download a model if one is downloadable.
|
|
943
|
+
*/
|
|
944
|
+
async downloadIfAvailable() {
|
|
945
|
+
const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
|
|
946
|
+
if (availability === Availability.DOWNLOADABLE) {
|
|
947
|
+
this.download();
|
|
948
|
+
}
|
|
949
|
+
return availability;
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Triggers out-of-band download of an on-device model.
|
|
896
953
|
*
|
|
897
|
-
*
|
|
898
|
-
*
|
|
954
|
+
* Chrome only downloads models as needed. Chrome knows a model is needed when code calls
|
|
955
|
+
* LanguageModel.create.
|
|
899
956
|
*
|
|
900
|
-
*
|
|
957
|
+
* Since Chrome manages the download, the SDK can only avoid redundant download requests by
|
|
958
|
+
* tracking if a download has previously been requested.
|
|
901
959
|
*/
|
|
902
|
-
|
|
903
|
-
if (
|
|
904
|
-
return
|
|
960
|
+
download() {
|
|
961
|
+
if (this.isDownloading) {
|
|
962
|
+
return;
|
|
905
963
|
}
|
|
906
|
-
|
|
907
|
-
|
|
964
|
+
this.isDownloading = true;
|
|
965
|
+
this.downloadPromise = this.languageModelProvider
|
|
966
|
+
?.create(this.onDeviceParams.createOptions)
|
|
967
|
+
.finally(() => {
|
|
968
|
+
this.isDownloading = false;
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Converts Firebase AI {@link Content} object to a Chrome {@link LanguageModelMessage} object.
|
|
973
|
+
*/
|
|
974
|
+
static async toLanguageModelMessage(content) {
|
|
975
|
+
const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
|
|
976
|
+
return {
|
|
977
|
+
role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
|
|
978
|
+
content: languageModelMessageContents
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Converts a Firebase AI Part object to a Chrome LanguageModelMessageContent object.
|
|
983
|
+
*/
|
|
984
|
+
static async toLanguageModelMessageContent(part) {
|
|
985
|
+
if (part.text) {
|
|
986
|
+
return {
|
|
987
|
+
type: 'text',
|
|
988
|
+
value: part.text
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
else if (part.inlineData) {
|
|
992
|
+
const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
|
|
993
|
+
const imageBlob = await formattedImageContent.blob();
|
|
994
|
+
const imageBitmap = await createImageBitmap(imageBlob);
|
|
995
|
+
return {
|
|
996
|
+
type: 'image',
|
|
997
|
+
value: imageBitmap
|
|
998
|
+
};
|
|
908
999
|
}
|
|
1000
|
+
throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
|
|
909
1001
|
}
|
|
910
1002
|
/**
|
|
911
|
-
* @
|
|
1003
|
+
* Converts a Firebase AI {@link Role} string to a {@link LanguageModelMessageRole} string.
|
|
912
1004
|
*/
|
|
913
|
-
static
|
|
914
|
-
|
|
1005
|
+
static toLanguageModelMessageRole(role) {
|
|
1006
|
+
// Assumes 'function' rule has been filtered by isOnDeviceRequest
|
|
1007
|
+
return role === 'model' ? 'assistant' : 'user';
|
|
915
1008
|
}
|
|
916
1009
|
/**
|
|
917
|
-
*
|
|
1010
|
+
* Abstracts Chrome session creation.
|
|
1011
|
+
*
|
|
1012
|
+
* Chrome uses a multi-turn session for all inference. Firebase AI uses single-turn for all
|
|
1013
|
+
* inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
|
|
1014
|
+
* inference.
|
|
1015
|
+
*
|
|
1016
|
+
* Chrome will remove a model from memory if it's no longer in use, so this method ensures a
|
|
1017
|
+
* new session is created before an old session is destroyed.
|
|
918
1018
|
*/
|
|
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
|
-
}
|
|
1019
|
+
async createSession() {
|
|
1020
|
+
if (!this.languageModelProvider) {
|
|
1021
|
+
throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
|
|
930
1022
|
}
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
1023
|
+
const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
|
|
1024
|
+
if (this.oldSession) {
|
|
1025
|
+
this.oldSession.destroy();
|
|
934
1026
|
}
|
|
935
|
-
|
|
1027
|
+
// Holds session reference, so model isn't unloaded from memory.
|
|
1028
|
+
this.oldSession = newSession;
|
|
1029
|
+
return newSession;
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
|
|
1033
|
+
*/
|
|
1034
|
+
static toResponse(text) {
|
|
1035
|
+
return {
|
|
1036
|
+
json: async () => ({
|
|
1037
|
+
candidates: [
|
|
1038
|
+
{
|
|
1039
|
+
content: {
|
|
1040
|
+
parts: [{ text }]
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
]
|
|
1044
|
+
})
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Formats string stream returned by Chrome as SSE returned by Firebase AI.
|
|
1049
|
+
*/
|
|
1050
|
+
static toStreamResponse(stream) {
|
|
1051
|
+
const encoder = new TextEncoder();
|
|
1052
|
+
return {
|
|
1053
|
+
body: stream.pipeThrough(new TransformStream({
|
|
1054
|
+
transform(chunk, controller) {
|
|
1055
|
+
const json = JSON.stringify({
|
|
1056
|
+
candidates: [
|
|
1057
|
+
{
|
|
1058
|
+
content: {
|
|
1059
|
+
role: 'model',
|
|
1060
|
+
parts: [{ text: chunk }]
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
]
|
|
1064
|
+
});
|
|
1065
|
+
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
|
1066
|
+
}
|
|
1067
|
+
}))
|
|
1068
|
+
};
|
|
936
1069
|
}
|
|
937
1070
|
}
|
|
938
|
-
|
|
1071
|
+
// Visible for testing
|
|
1072
|
+
ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
|
|
939
1073
|
/**
|
|
940
|
-
*
|
|
941
|
-
* Copyright 2024 Google LLC
|
|
942
|
-
*
|
|
943
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
944
|
-
* you may not use this file except in compliance with the License.
|
|
945
|
-
* You may obtain a copy of the License at
|
|
946
|
-
*
|
|
947
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
948
|
-
*
|
|
949
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
950
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
951
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
952
|
-
* See the License for the specific language governing permissions and
|
|
953
|
-
* limitations under the License.
|
|
1074
|
+
* Creates a ChromeAdapterImpl on demand.
|
|
954
1075
|
*/
|
|
955
|
-
|
|
1076
|
+
function chromeAdapterFactory(mode, window, params) {
|
|
1077
|
+
// Do not initialize a ChromeAdapter if we are not in hybrid mode.
|
|
1078
|
+
if (typeof window !== 'undefined' && mode) {
|
|
1079
|
+
return new ChromeAdapterImpl(window.LanguageModel, mode, params);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
956
1082
|
|
|
957
1083
|
/**
|
|
958
1084
|
* @license
|
|
@@ -970,8 +1096,205 @@ const logger = new Logger('@firebase/vertexai');
|
|
|
970
1096
|
* See the License for the specific language governing permissions and
|
|
971
1097
|
* limitations under the License.
|
|
972
1098
|
*/
|
|
973
|
-
|
|
974
|
-
(
|
|
1099
|
+
class AIService {
|
|
1100
|
+
constructor(app, backend, authProvider, appCheckProvider, chromeAdapterFactory) {
|
|
1101
|
+
this.app = app;
|
|
1102
|
+
this.backend = backend;
|
|
1103
|
+
this.chromeAdapterFactory = chromeAdapterFactory;
|
|
1104
|
+
const appCheck = appCheckProvider?.getImmediate({ optional: true });
|
|
1105
|
+
const auth = authProvider?.getImmediate({ optional: true });
|
|
1106
|
+
this.auth = auth || null;
|
|
1107
|
+
this.appCheck = appCheck || null;
|
|
1108
|
+
if (backend instanceof VertexAIBackend) {
|
|
1109
|
+
this.location = backend.location;
|
|
1110
|
+
}
|
|
1111
|
+
else {
|
|
1112
|
+
this.location = '';
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
_delete() {
|
|
1116
|
+
return Promise.resolve();
|
|
1117
|
+
}
|
|
1118
|
+
set options(optionsToSet) {
|
|
1119
|
+
this._options = optionsToSet;
|
|
1120
|
+
}
|
|
1121
|
+
get options() {
|
|
1122
|
+
return this._options;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* @license
|
|
1128
|
+
* Copyright 2025 Google LLC
|
|
1129
|
+
*
|
|
1130
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1131
|
+
* you may not use this file except in compliance with the License.
|
|
1132
|
+
* You may obtain a copy of the License at
|
|
1133
|
+
*
|
|
1134
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1135
|
+
*
|
|
1136
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1137
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1138
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1139
|
+
* See the License for the specific language governing permissions and
|
|
1140
|
+
* limitations under the License.
|
|
1141
|
+
*/
|
|
1142
|
+
function factory(container, { instanceIdentifier }) {
|
|
1143
|
+
if (!instanceIdentifier) {
|
|
1144
|
+
throw new AIError(AIErrorCode.ERROR, 'AIService instance identifier is undefined.');
|
|
1145
|
+
}
|
|
1146
|
+
const backend = decodeInstanceIdentifier(instanceIdentifier);
|
|
1147
|
+
// getImmediate for FirebaseApp will always succeed
|
|
1148
|
+
const app = container.getProvider('app').getImmediate();
|
|
1149
|
+
const auth = container.getProvider('auth-internal');
|
|
1150
|
+
const appCheckProvider = container.getProvider('app-check-internal');
|
|
1151
|
+
return new AIService(app, backend, auth, appCheckProvider, chromeAdapterFactory);
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/**
|
|
1155
|
+
* @license
|
|
1156
|
+
* Copyright 2025 Google LLC
|
|
1157
|
+
*
|
|
1158
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1159
|
+
* you may not use this file except in compliance with the License.
|
|
1160
|
+
* You may obtain a copy of the License at
|
|
1161
|
+
*
|
|
1162
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1163
|
+
*
|
|
1164
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1165
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1166
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1167
|
+
* See the License for the specific language governing permissions and
|
|
1168
|
+
* limitations under the License.
|
|
1169
|
+
*/
|
|
1170
|
+
/**
|
|
1171
|
+
* Base class for Firebase AI model APIs.
|
|
1172
|
+
*
|
|
1173
|
+
* Instances of this class are associated with a specific Firebase AI {@link Backend}
|
|
1174
|
+
* and provide methods for interacting with the configured generative model.
|
|
1175
|
+
*
|
|
1176
|
+
* @public
|
|
1177
|
+
*/
|
|
1178
|
+
class AIModel {
|
|
1179
|
+
/**
|
|
1180
|
+
* Constructs a new instance of the {@link AIModel} class.
|
|
1181
|
+
*
|
|
1182
|
+
* This constructor should only be called from subclasses that provide
|
|
1183
|
+
* a model API.
|
|
1184
|
+
*
|
|
1185
|
+
* @param ai - an {@link AI} instance.
|
|
1186
|
+
* @param modelName - The name of the model being used. It can be in one of the following formats:
|
|
1187
|
+
* - `my-model` (short name, will resolve to `publishers/google/models/my-model`)
|
|
1188
|
+
* - `models/my-model` (will resolve to `publishers/google/models/my-model`)
|
|
1189
|
+
* - `publishers/my-publisher/models/my-model` (fully qualified model name)
|
|
1190
|
+
*
|
|
1191
|
+
* @throws If the `apiKey` or `projectId` fields are missing in your
|
|
1192
|
+
* Firebase config.
|
|
1193
|
+
*
|
|
1194
|
+
* @internal
|
|
1195
|
+
*/
|
|
1196
|
+
constructor(ai, modelName) {
|
|
1197
|
+
if (!ai.app?.options?.apiKey) {
|
|
1198
|
+
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.`);
|
|
1199
|
+
}
|
|
1200
|
+
else if (!ai.app?.options?.projectId) {
|
|
1201
|
+
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.`);
|
|
1202
|
+
}
|
|
1203
|
+
else if (!ai.app?.options?.appId) {
|
|
1204
|
+
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.`);
|
|
1205
|
+
}
|
|
1206
|
+
else {
|
|
1207
|
+
this._apiSettings = {
|
|
1208
|
+
apiKey: ai.app.options.apiKey,
|
|
1209
|
+
project: ai.app.options.projectId,
|
|
1210
|
+
appId: ai.app.options.appId,
|
|
1211
|
+
automaticDataCollectionEnabled: ai.app.automaticDataCollectionEnabled,
|
|
1212
|
+
location: ai.location,
|
|
1213
|
+
backend: ai.backend
|
|
1214
|
+
};
|
|
1215
|
+
if (_isFirebaseServerApp(ai.app) && ai.app.settings.appCheckToken) {
|
|
1216
|
+
const token = ai.app.settings.appCheckToken;
|
|
1217
|
+
this._apiSettings.getAppCheckToken = () => {
|
|
1218
|
+
return Promise.resolve({ token });
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
else if (ai.appCheck) {
|
|
1222
|
+
if (ai.options?.useLimitedUseAppCheckTokens) {
|
|
1223
|
+
this._apiSettings.getAppCheckToken = () => ai.appCheck.getLimitedUseToken();
|
|
1224
|
+
}
|
|
1225
|
+
else {
|
|
1226
|
+
this._apiSettings.getAppCheckToken = () => ai.appCheck.getToken();
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
if (ai.auth) {
|
|
1230
|
+
this._apiSettings.getAuthToken = () => ai.auth.getToken();
|
|
1231
|
+
}
|
|
1232
|
+
this.model = AIModel.normalizeModelName(modelName, this._apiSettings.backend.backendType);
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* Normalizes the given model name to a fully qualified model resource name.
|
|
1237
|
+
*
|
|
1238
|
+
* @param modelName - The model name to normalize.
|
|
1239
|
+
* @returns The fully qualified model resource name.
|
|
1240
|
+
*
|
|
1241
|
+
* @internal
|
|
1242
|
+
*/
|
|
1243
|
+
static normalizeModelName(modelName, backendType) {
|
|
1244
|
+
if (backendType === BackendType.GOOGLE_AI) {
|
|
1245
|
+
return AIModel.normalizeGoogleAIModelName(modelName);
|
|
1246
|
+
}
|
|
1247
|
+
else {
|
|
1248
|
+
return AIModel.normalizeVertexAIModelName(modelName);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
/**
|
|
1252
|
+
* @internal
|
|
1253
|
+
*/
|
|
1254
|
+
static normalizeGoogleAIModelName(modelName) {
|
|
1255
|
+
return `models/${modelName}`;
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* @internal
|
|
1259
|
+
*/
|
|
1260
|
+
static normalizeVertexAIModelName(modelName) {
|
|
1261
|
+
let model;
|
|
1262
|
+
if (modelName.includes('/')) {
|
|
1263
|
+
if (modelName.startsWith('models/')) {
|
|
1264
|
+
// Add 'publishers/google' if the user is only passing in 'models/model-name'.
|
|
1265
|
+
model = `publishers/google/${modelName}`;
|
|
1266
|
+
}
|
|
1267
|
+
else {
|
|
1268
|
+
// Any other custom format (e.g. tuned models) must be passed in correctly.
|
|
1269
|
+
model = modelName;
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
else {
|
|
1273
|
+
// If path is not included, assume it's a non-tuned model.
|
|
1274
|
+
model = `publishers/google/models/${modelName}`;
|
|
1275
|
+
}
|
|
1276
|
+
return model;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* @license
|
|
1282
|
+
* Copyright 2024 Google LLC
|
|
1283
|
+
*
|
|
1284
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1285
|
+
* you may not use this file except in compliance with the License.
|
|
1286
|
+
* You may obtain a copy of the License at
|
|
1287
|
+
*
|
|
1288
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1289
|
+
*
|
|
1290
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1291
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1292
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1293
|
+
* See the License for the specific language governing permissions and
|
|
1294
|
+
* limitations under the License.
|
|
1295
|
+
*/
|
|
1296
|
+
var Task;
|
|
1297
|
+
(function (Task) {
|
|
975
1298
|
Task["GENERATE_CONTENT"] = "generateContent";
|
|
976
1299
|
Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
|
|
977
1300
|
Task["COUNT_TOKENS"] = "countTokens";
|
|
@@ -3606,317 +3929,11 @@ function getLiveGenerativeModel(ai, modelParams) {
|
|
|
3606
3929
|
return new LiveGenerativeModel(ai, modelParams, webSocketHandler);
|
|
3607
3930
|
}
|
|
3608
3931
|
|
|
3609
|
-
/**
|
|
3610
|
-
* @internal
|
|
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
3932
|
/**
|
|
3905
3933
|
* The Firebase AI Web SDK.
|
|
3906
3934
|
*
|
|
3907
3935
|
* @packageDocumentation
|
|
3908
3936
|
*/
|
|
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
3937
|
function registerAI() {
|
|
3921
3938
|
_registerComponent(new Component(AI_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
|
|
3922
3939
|
registerVersion(name, version);
|