@firebase/ai 2.2.1 → 2.3.0-canary.cb3bdd812

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