@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.
@@ -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";
7
+ var version = "2.3.0-canary.cb3bdd812";
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
@@ -297,14 +353,51 @@ const ResponseModality = {
297
353
  AUDIO: 'AUDIO'
298
354
  };
299
355
  /**
300
- * <b>(EXPERIMENTAL)</b>
301
356
  * Determines whether inference happens on-device or in-cloud.
302
- * @public
357
+ *
358
+ * @remarks
359
+ * <b>PREFER_ON_DEVICE:</b> Attempt to make inference calls using an
360
+ * on-device model. If on-device inference is not available, the SDK
361
+ * will fall back to using a cloud-hosted model.
362
+ * <br/>
363
+ * <b>ONLY_ON_DEVICE:</b> Only attempt to make inference calls using an
364
+ * on-device model. The SDK will not fall back to a cloud-hosted model.
365
+ * If on-device inference is not available, inference methods will throw.
366
+ * <br/>
367
+ * <b>ONLY_IN_CLOUD:</b> Only attempt to make inference calls using a
368
+ * cloud-hosted model. The SDK will not fall back to an on-device model.
369
+ * <br/>
370
+ * <b>PREFER_IN_CLOUD:</b> Attempt to make inference calls to a
371
+ * cloud-hosted model. If not available, the SDK will fall back to an
372
+ * on-device model.
373
+ *
374
+ * @beta
303
375
  */
304
376
  const InferenceMode = {
305
377
  'PREFER_ON_DEVICE': 'prefer_on_device',
306
378
  'ONLY_ON_DEVICE': 'only_on_device',
307
- 'ONLY_IN_CLOUD': 'only_in_cloud'
379
+ 'ONLY_IN_CLOUD': 'only_in_cloud',
380
+ 'PREFER_IN_CLOUD': 'prefer_in_cloud'
381
+ };
382
+ /**
383
+ * Represents the result of the code execution.
384
+ *
385
+ * @public
386
+ */
387
+ const Outcome = {
388
+ UNSPECIFIED: 'OUTCOME_UNSPECIFIED',
389
+ OK: 'OUTCOME_OK',
390
+ FAILED: 'OUTCOME_FAILED',
391
+ DEADLINE_EXCEEDED: 'OUTCOME_DEADLINE_EXCEEDED'
392
+ };
393
+ /**
394
+ * The programming language of the code.
395
+ *
396
+ * @public
397
+ */
398
+ const Language = {
399
+ UNSPECIFIED: 'LANGUAGE_UNSPECIFIED',
400
+ PYTHON: 'PYTHON'
308
401
  };
309
402
 
310
403
  /**
@@ -653,105 +746,6 @@ class VertexAIBackend extends Backend {
653
746
  }
654
747
  }
655
748
 
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
749
  /**
756
750
  * @license
757
751
  * Copyright 2025 Google LLC
@@ -812,7 +806,7 @@ function decodeInstanceIdentifier(instanceIdentifier) {
812
806
 
813
807
  /**
814
808
  * @license
815
- * Copyright 2025 Google LLC
809
+ * Copyright 2024 Google LLC
816
810
  *
817
811
  * Licensed under the Apache License, Version 2.0 (the "License");
818
812
  * you may not use this file except in compliance with the License.
@@ -826,113 +820,300 @@ function decodeInstanceIdentifier(instanceIdentifier) {
826
820
  * See the License for the specific language governing permissions and
827
821
  * limitations under the License.
828
822
  */
823
+ const logger = new Logger('@firebase/vertexai');
824
+
829
825
  /**
830
- * Base class for Firebase AI model APIs.
826
+ * @internal
827
+ */
828
+ var Availability;
829
+ (function (Availability) {
830
+ Availability["UNAVAILABLE"] = "unavailable";
831
+ Availability["DOWNLOADABLE"] = "downloadable";
832
+ Availability["DOWNLOADING"] = "downloading";
833
+ Availability["AVAILABLE"] = "available";
834
+ })(Availability || (Availability = {}));
835
+
836
+ /**
837
+ * @license
838
+ * Copyright 2025 Google LLC
831
839
  *
832
- * Instances of this class are associated with a specific Firebase AI {@link Backend}
833
- * and provide methods for interacting with the configured generative model.
840
+ * Licensed under the Apache License, Version 2.0 (the "License");
841
+ * you may not use this file except in compliance with the License.
842
+ * You may obtain a copy of the License at
834
843
  *
835
- * @public
844
+ * http://www.apache.org/licenses/LICENSE-2.0
845
+ *
846
+ * Unless required by applicable law or agreed to in writing, software
847
+ * distributed under the License is distributed on an "AS IS" BASIS,
848
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
849
+ * See the License for the specific language governing permissions and
850
+ * limitations under the License.
836
851
  */
837
- class AIModel {
852
+ /**
853
+ * Defines an inference "backend" that uses Chrome's on-device model,
854
+ * and encapsulates logic for detecting when on-device inference is
855
+ * possible.
856
+ */
857
+ class ChromeAdapterImpl {
858
+ constructor(languageModelProvider, mode, onDeviceParams = {
859
+ createOptions: {
860
+ // Defaults to support image inputs for convenience.
861
+ expectedInputs: [{ type: 'image' }]
862
+ }
863
+ }) {
864
+ this.languageModelProvider = languageModelProvider;
865
+ this.mode = mode;
866
+ this.onDeviceParams = onDeviceParams;
867
+ this.isDownloading = false;
868
+ }
838
869
  /**
839
- * Constructs a new instance of the {@link AIModel} class.
840
- *
841
- * This constructor should only be called from subclasses that provide
842
- * a model API.
870
+ * Checks if a given request can be made on-device.
843
871
  *
844
- * @param ai - an {@link AI} instance.
845
- * @param modelName - The name of the model being used. It can be in one of the following formats:
846
- * - `my-model` (short name, will resolve to `publishers/google/models/my-model`)
847
- * - `models/my-model` (will resolve to `publishers/google/models/my-model`)
848
- * - `publishers/my-publisher/models/my-model` (fully qualified model name)
872
+ * Encapsulates a few concerns:
873
+ * the mode
874
+ * API existence
875
+ * prompt formatting
876
+ * model availability, including triggering download if necessary
849
877
  *
850
- * @throws If the `apiKey` or `projectId` fields are missing in your
851
- * Firebase config.
852
878
  *
853
- * @internal
879
+ * Pros: callers needn't be concerned with details of on-device availability.</p>
880
+ * Cons: this method spans a few concerns and splits request validation from usage.
881
+ * If instance variables weren't already part of the API, we could consider a better
882
+ * separation of concerns.
854
883
  */
855
- constructor(ai, modelName) {
856
- if (!ai.app?.options?.apiKey) {
857
- 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.`);
858
- }
859
- else if (!ai.app?.options?.projectId) {
860
- throw new AIError(AIErrorCode.NO_PROJECT_ID, `The "projectId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid project ID.`);
884
+ async isAvailable(request) {
885
+ if (!this.mode) {
886
+ logger.debug(`On-device inference unavailable because mode is undefined.`);
887
+ return false;
861
888
  }
862
- else if (!ai.app?.options?.appId) {
863
- 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.`);
889
+ if (this.mode === InferenceMode.ONLY_IN_CLOUD) {
890
+ logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
891
+ return false;
864
892
  }
865
- else {
866
- this._apiSettings = {
867
- apiKey: ai.app.options.apiKey,
868
- project: ai.app.options.projectId,
869
- appId: ai.app.options.appId,
870
- automaticDataCollectionEnabled: ai.app.automaticDataCollectionEnabled,
871
- location: ai.location,
872
- backend: ai.backend
873
- };
874
- if (_isFirebaseServerApp(ai.app) && ai.app.settings.appCheckToken) {
875
- const token = ai.app.settings.appCheckToken;
876
- this._apiSettings.getAppCheckToken = () => {
877
- return Promise.resolve({ token });
878
- };
893
+ // Triggers out-of-band download so model will eventually become available.
894
+ const availability = await this.downloadIfAvailable();
895
+ if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
896
+ // If it will never be available due to API inavailability, throw.
897
+ if (availability === Availability.UNAVAILABLE) {
898
+ throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
879
899
  }
880
- else if (ai.appCheck) {
881
- if (ai.options?.useLimitedUseAppCheckTokens) {
882
- this._apiSettings.getAppCheckToken = () => ai.appCheck.getLimitedUseToken();
883
- }
884
- else {
885
- this._apiSettings.getAppCheckToken = () => ai.appCheck.getToken();
886
- }
900
+ else if (availability === Availability.DOWNLOADABLE ||
901
+ availability === Availability.DOWNLOADING) {
902
+ // TODO(chholland): Better user experience during download - progress?
903
+ logger.debug(`Waiting for download of LanguageModel to complete.`);
904
+ await this.downloadPromise;
905
+ return true;
887
906
  }
888
- if (ai.auth) {
889
- this._apiSettings.getAuthToken = () => ai.auth.getToken();
907
+ return true;
908
+ }
909
+ // Applies prefer_on_device logic.
910
+ if (availability !== Availability.AVAILABLE) {
911
+ logger.debug(`On-device inference unavailable because availability is "${availability}".`);
912
+ return false;
913
+ }
914
+ if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
915
+ logger.debug(`On-device inference unavailable because request is incompatible.`);
916
+ return false;
917
+ }
918
+ return true;
919
+ }
920
+ /**
921
+ * Generates content on device.
922
+ *
923
+ * @remarks
924
+ * This is comparable to {@link GenerativeModel.generateContent} for generating content in
925
+ * Cloud.
926
+ * @param request - a standard Firebase AI {@link GenerateContentRequest}
927
+ * @returns {@link Response}, so we can reuse common response formatting.
928
+ */
929
+ async generateContent(request) {
930
+ const session = await this.createSession();
931
+ const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
932
+ const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
933
+ return ChromeAdapterImpl.toResponse(text);
934
+ }
935
+ /**
936
+ * Generates content stream on device.
937
+ *
938
+ * @remarks
939
+ * This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
940
+ * Cloud.
941
+ * @param request - a standard Firebase AI {@link GenerateContentRequest}
942
+ * @returns {@link Response}, so we can reuse common response formatting.
943
+ */
944
+ async generateContentStream(request) {
945
+ const session = await this.createSession();
946
+ const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
947
+ const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
948
+ return ChromeAdapterImpl.toStreamResponse(stream);
949
+ }
950
+ async countTokens(_request) {
951
+ throw new AIError(AIErrorCode.REQUEST_ERROR, 'Count Tokens is not yet available for on-device model.');
952
+ }
953
+ /**
954
+ * Asserts inference for the given request can be performed by an on-device model.
955
+ */
956
+ static isOnDeviceRequest(request) {
957
+ // Returns false if the prompt is empty.
958
+ if (request.contents.length === 0) {
959
+ logger.debug('Empty prompt rejected for on-device inference.');
960
+ return false;
961
+ }
962
+ for (const content of request.contents) {
963
+ if (content.role === 'function') {
964
+ logger.debug(`"Function" role rejected for on-device inference.`);
965
+ return false;
966
+ }
967
+ // Returns false if request contains an image with an unsupported mime type.
968
+ for (const part of content.parts) {
969
+ if (part.inlineData &&
970
+ ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
971
+ logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
972
+ return false;
973
+ }
890
974
  }
891
- this.model = AIModel.normalizeModelName(modelName, this._apiSettings.backend.backendType);
892
975
  }
976
+ return true;
893
977
  }
894
978
  /**
895
- * Normalizes the given model name to a fully qualified model resource name.
979
+ * Encapsulates logic to get availability and download a model if one is downloadable.
980
+ */
981
+ async downloadIfAvailable() {
982
+ const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
983
+ if (availability === Availability.DOWNLOADABLE) {
984
+ this.download();
985
+ }
986
+ return availability;
987
+ }
988
+ /**
989
+ * Triggers out-of-band download of an on-device model.
896
990
  *
897
- * @param modelName - The model name to normalize.
898
- * @returns The fully qualified model resource name.
991
+ * Chrome only downloads models as needed. Chrome knows a model is needed when code calls
992
+ * LanguageModel.create.
899
993
  *
900
- * @internal
994
+ * Since Chrome manages the download, the SDK can only avoid redundant download requests by
995
+ * tracking if a download has previously been requested.
901
996
  */
902
- static normalizeModelName(modelName, backendType) {
903
- if (backendType === BackendType.GOOGLE_AI) {
904
- return AIModel.normalizeGoogleAIModelName(modelName);
997
+ download() {
998
+ if (this.isDownloading) {
999
+ return;
905
1000
  }
906
- else {
907
- return AIModel.normalizeVertexAIModelName(modelName);
1001
+ this.isDownloading = true;
1002
+ this.downloadPromise = this.languageModelProvider
1003
+ ?.create(this.onDeviceParams.createOptions)
1004
+ .finally(() => {
1005
+ this.isDownloading = false;
1006
+ });
1007
+ }
1008
+ /**
1009
+ * Converts Firebase AI {@link Content} object to a Chrome {@link LanguageModelMessage} object.
1010
+ */
1011
+ static async toLanguageModelMessage(content) {
1012
+ const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
1013
+ return {
1014
+ role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
1015
+ content: languageModelMessageContents
1016
+ };
1017
+ }
1018
+ /**
1019
+ * Converts a Firebase AI Part object to a Chrome LanguageModelMessageContent object.
1020
+ */
1021
+ static async toLanguageModelMessageContent(part) {
1022
+ if (part.text) {
1023
+ return {
1024
+ type: 'text',
1025
+ value: part.text
1026
+ };
1027
+ }
1028
+ else if (part.inlineData) {
1029
+ const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
1030
+ const imageBlob = await formattedImageContent.blob();
1031
+ const imageBitmap = await createImageBitmap(imageBlob);
1032
+ return {
1033
+ type: 'image',
1034
+ value: imageBitmap
1035
+ };
908
1036
  }
1037
+ throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
909
1038
  }
910
1039
  /**
911
- * @internal
1040
+ * Converts a Firebase AI {@link Role} string to a {@link LanguageModelMessageRole} string.
912
1041
  */
913
- static normalizeGoogleAIModelName(modelName) {
914
- return `models/${modelName}`;
1042
+ static toLanguageModelMessageRole(role) {
1043
+ // Assumes 'function' rule has been filtered by isOnDeviceRequest
1044
+ return role === 'model' ? 'assistant' : 'user';
915
1045
  }
916
1046
  /**
917
- * @internal
1047
+ * Abstracts Chrome session creation.
1048
+ *
1049
+ * Chrome uses a multi-turn session for all inference. Firebase AI uses single-turn for all
1050
+ * inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
1051
+ * inference.
1052
+ *
1053
+ * Chrome will remove a model from memory if it's no longer in use, so this method ensures a
1054
+ * new session is created before an old session is destroyed.
918
1055
  */
919
- static normalizeVertexAIModelName(modelName) {
920
- let model;
921
- if (modelName.includes('/')) {
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
- }
1056
+ async createSession() {
1057
+ if (!this.languageModelProvider) {
1058
+ throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
930
1059
  }
931
- else {
932
- // If path is not included, assume it's a non-tuned model.
933
- model = `publishers/google/models/${modelName}`;
1060
+ const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
1061
+ if (this.oldSession) {
1062
+ this.oldSession.destroy();
934
1063
  }
935
- return model;
1064
+ // Holds session reference, so model isn't unloaded from memory.
1065
+ this.oldSession = newSession;
1066
+ return newSession;
1067
+ }
1068
+ /**
1069
+ * Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
1070
+ */
1071
+ static toResponse(text) {
1072
+ return {
1073
+ json: async () => ({
1074
+ candidates: [
1075
+ {
1076
+ content: {
1077
+ parts: [{ text }]
1078
+ }
1079
+ }
1080
+ ]
1081
+ })
1082
+ };
1083
+ }
1084
+ /**
1085
+ * Formats string stream returned by Chrome as SSE returned by Firebase AI.
1086
+ */
1087
+ static toStreamResponse(stream) {
1088
+ const encoder = new TextEncoder();
1089
+ return {
1090
+ body: stream.pipeThrough(new TransformStream({
1091
+ transform(chunk, controller) {
1092
+ const json = JSON.stringify({
1093
+ candidates: [
1094
+ {
1095
+ content: {
1096
+ role: 'model',
1097
+ parts: [{ text: chunk }]
1098
+ }
1099
+ }
1100
+ ]
1101
+ });
1102
+ controller.enqueue(encoder.encode(`data: ${json}\n\n`));
1103
+ }
1104
+ }))
1105
+ };
1106
+ }
1107
+ }
1108
+ // Visible for testing
1109
+ ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
1110
+ /**
1111
+ * Creates a ChromeAdapterImpl on demand.
1112
+ */
1113
+ function chromeAdapterFactory(mode, window, params) {
1114
+ // Do not initialize a ChromeAdapter if we are not in hybrid mode.
1115
+ if (typeof window !== 'undefined' && mode) {
1116
+ return new ChromeAdapterImpl(window.LanguageModel, mode, params);
936
1117
  }
937
1118
  }
938
1119
 
@@ -952,7 +1133,186 @@ class AIModel {
952
1133
  * See the License for the specific language governing permissions and
953
1134
  * limitations under the License.
954
1135
  */
955
- const logger = new Logger('@firebase/vertexai');
1136
+ class AIService {
1137
+ constructor(app, backend, authProvider, appCheckProvider, chromeAdapterFactory) {
1138
+ this.app = app;
1139
+ this.backend = backend;
1140
+ this.chromeAdapterFactory = chromeAdapterFactory;
1141
+ const appCheck = appCheckProvider?.getImmediate({ optional: true });
1142
+ const auth = authProvider?.getImmediate({ optional: true });
1143
+ this.auth = auth || null;
1144
+ this.appCheck = appCheck || null;
1145
+ if (backend instanceof VertexAIBackend) {
1146
+ this.location = backend.location;
1147
+ }
1148
+ else {
1149
+ this.location = '';
1150
+ }
1151
+ }
1152
+ _delete() {
1153
+ return Promise.resolve();
1154
+ }
1155
+ set options(optionsToSet) {
1156
+ this._options = optionsToSet;
1157
+ }
1158
+ get options() {
1159
+ return this._options;
1160
+ }
1161
+ }
1162
+
1163
+ /**
1164
+ * @license
1165
+ * Copyright 2025 Google LLC
1166
+ *
1167
+ * Licensed under the Apache License, Version 2.0 (the "License");
1168
+ * you may not use this file except in compliance with the License.
1169
+ * You may obtain a copy of the License at
1170
+ *
1171
+ * http://www.apache.org/licenses/LICENSE-2.0
1172
+ *
1173
+ * Unless required by applicable law or agreed to in writing, software
1174
+ * distributed under the License is distributed on an "AS IS" BASIS,
1175
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1176
+ * See the License for the specific language governing permissions and
1177
+ * limitations under the License.
1178
+ */
1179
+ function factory(container, { instanceIdentifier }) {
1180
+ if (!instanceIdentifier) {
1181
+ throw new AIError(AIErrorCode.ERROR, 'AIService instance identifier is undefined.');
1182
+ }
1183
+ const backend = decodeInstanceIdentifier(instanceIdentifier);
1184
+ // getImmediate for FirebaseApp will always succeed
1185
+ const app = container.getProvider('app').getImmediate();
1186
+ const auth = container.getProvider('auth-internal');
1187
+ const appCheckProvider = container.getProvider('app-check-internal');
1188
+ return new AIService(app, backend, auth, appCheckProvider, chromeAdapterFactory);
1189
+ }
1190
+
1191
+ /**
1192
+ * @license
1193
+ * Copyright 2025 Google LLC
1194
+ *
1195
+ * Licensed under the Apache License, Version 2.0 (the "License");
1196
+ * you may not use this file except in compliance with the License.
1197
+ * You may obtain a copy of the License at
1198
+ *
1199
+ * http://www.apache.org/licenses/LICENSE-2.0
1200
+ *
1201
+ * Unless required by applicable law or agreed to in writing, software
1202
+ * distributed under the License is distributed on an "AS IS" BASIS,
1203
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1204
+ * See the License for the specific language governing permissions and
1205
+ * limitations under the License.
1206
+ */
1207
+ /**
1208
+ * Base class for Firebase AI model APIs.
1209
+ *
1210
+ * Instances of this class are associated with a specific Firebase AI {@link Backend}
1211
+ * and provide methods for interacting with the configured generative model.
1212
+ *
1213
+ * @public
1214
+ */
1215
+ class AIModel {
1216
+ /**
1217
+ * Constructs a new instance of the {@link AIModel} class.
1218
+ *
1219
+ * This constructor should only be called from subclasses that provide
1220
+ * a model API.
1221
+ *
1222
+ * @param ai - an {@link AI} instance.
1223
+ * @param modelName - The name of the model being used. It can be in one of the following formats:
1224
+ * - `my-model` (short name, will resolve to `publishers/google/models/my-model`)
1225
+ * - `models/my-model` (will resolve to `publishers/google/models/my-model`)
1226
+ * - `publishers/my-publisher/models/my-model` (fully qualified model name)
1227
+ *
1228
+ * @throws If the `apiKey` or `projectId` fields are missing in your
1229
+ * Firebase config.
1230
+ *
1231
+ * @internal
1232
+ */
1233
+ constructor(ai, modelName) {
1234
+ if (!ai.app?.options?.apiKey) {
1235
+ 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.`);
1236
+ }
1237
+ else if (!ai.app?.options?.projectId) {
1238
+ 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.`);
1239
+ }
1240
+ else if (!ai.app?.options?.appId) {
1241
+ 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.`);
1242
+ }
1243
+ else {
1244
+ this._apiSettings = {
1245
+ apiKey: ai.app.options.apiKey,
1246
+ project: ai.app.options.projectId,
1247
+ appId: ai.app.options.appId,
1248
+ automaticDataCollectionEnabled: ai.app.automaticDataCollectionEnabled,
1249
+ location: ai.location,
1250
+ backend: ai.backend
1251
+ };
1252
+ if (_isFirebaseServerApp(ai.app) && ai.app.settings.appCheckToken) {
1253
+ const token = ai.app.settings.appCheckToken;
1254
+ this._apiSettings.getAppCheckToken = () => {
1255
+ return Promise.resolve({ token });
1256
+ };
1257
+ }
1258
+ else if (ai.appCheck) {
1259
+ if (ai.options?.useLimitedUseAppCheckTokens) {
1260
+ this._apiSettings.getAppCheckToken = () => ai.appCheck.getLimitedUseToken();
1261
+ }
1262
+ else {
1263
+ this._apiSettings.getAppCheckToken = () => ai.appCheck.getToken();
1264
+ }
1265
+ }
1266
+ if (ai.auth) {
1267
+ this._apiSettings.getAuthToken = () => ai.auth.getToken();
1268
+ }
1269
+ this.model = AIModel.normalizeModelName(modelName, this._apiSettings.backend.backendType);
1270
+ }
1271
+ }
1272
+ /**
1273
+ * Normalizes the given model name to a fully qualified model resource name.
1274
+ *
1275
+ * @param modelName - The model name to normalize.
1276
+ * @returns The fully qualified model resource name.
1277
+ *
1278
+ * @internal
1279
+ */
1280
+ static normalizeModelName(modelName, backendType) {
1281
+ if (backendType === BackendType.GOOGLE_AI) {
1282
+ return AIModel.normalizeGoogleAIModelName(modelName);
1283
+ }
1284
+ else {
1285
+ return AIModel.normalizeVertexAIModelName(modelName);
1286
+ }
1287
+ }
1288
+ /**
1289
+ * @internal
1290
+ */
1291
+ static normalizeGoogleAIModelName(modelName) {
1292
+ return `models/${modelName}`;
1293
+ }
1294
+ /**
1295
+ * @internal
1296
+ */
1297
+ static normalizeVertexAIModelName(modelName) {
1298
+ let model;
1299
+ if (modelName.includes('/')) {
1300
+ if (modelName.startsWith('models/')) {
1301
+ // Add 'publishers/google' if the user is only passing in 'models/model-name'.
1302
+ model = `publishers/google/${modelName}`;
1303
+ }
1304
+ else {
1305
+ // Any other custom format (e.g. tuned models) must be passed in correctly.
1306
+ model = modelName;
1307
+ }
1308
+ }
1309
+ else {
1310
+ // If path is not included, assume it's a non-tuned model.
1311
+ model = `publishers/google/models/${modelName}`;
1312
+ }
1313
+ return model;
1314
+ }
1315
+ }
956
1316
 
957
1317
  /**
958
1318
  * @license
@@ -1734,6 +2094,72 @@ function aggregateResponses(responses) {
1734
2094
  return aggregatedResponse;
1735
2095
  }
1736
2096
 
2097
+ /**
2098
+ * @license
2099
+ * Copyright 2025 Google LLC
2100
+ *
2101
+ * Licensed under the Apache License, Version 2.0 (the "License");
2102
+ * you may not use this file except in compliance with the License.
2103
+ * You may obtain a copy of the License at
2104
+ *
2105
+ * http://www.apache.org/licenses/LICENSE-2.0
2106
+ *
2107
+ * Unless required by applicable law or agreed to in writing, software
2108
+ * distributed under the License is distributed on an "AS IS" BASIS,
2109
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2110
+ * See the License for the specific language governing permissions and
2111
+ * limitations under the License.
2112
+ */
2113
+ const errorsCausingFallback = [
2114
+ // most network errors
2115
+ AIErrorCode.FETCH_ERROR,
2116
+ // fallback code for all other errors in makeRequest
2117
+ AIErrorCode.ERROR,
2118
+ // error due to API not being enabled in project
2119
+ AIErrorCode.API_NOT_ENABLED
2120
+ ];
2121
+ /**
2122
+ * Dispatches a request to the appropriate backend (on-device or in-cloud)
2123
+ * based on the inference mode.
2124
+ *
2125
+ * @param request - The request to be sent.
2126
+ * @param chromeAdapter - The on-device model adapter.
2127
+ * @param onDeviceCall - The function to call for on-device inference.
2128
+ * @param inCloudCall - The function to call for in-cloud inference.
2129
+ * @returns The response from the backend.
2130
+ */
2131
+ async function callCloudOrDevice(request, chromeAdapter, onDeviceCall, inCloudCall) {
2132
+ if (!chromeAdapter) {
2133
+ return inCloudCall();
2134
+ }
2135
+ switch (chromeAdapter.mode) {
2136
+ case InferenceMode.ONLY_ON_DEVICE:
2137
+ if (await chromeAdapter.isAvailable(request)) {
2138
+ return onDeviceCall();
2139
+ }
2140
+ throw new AIError(AIErrorCode.UNSUPPORTED, 'Inference mode is ONLY_ON_DEVICE, but an on-device model is not available.');
2141
+ case InferenceMode.ONLY_IN_CLOUD:
2142
+ return inCloudCall();
2143
+ case InferenceMode.PREFER_IN_CLOUD:
2144
+ try {
2145
+ return await inCloudCall();
2146
+ }
2147
+ catch (e) {
2148
+ if (e instanceof AIError && errorsCausingFallback.includes(e.code)) {
2149
+ return onDeviceCall();
2150
+ }
2151
+ throw e;
2152
+ }
2153
+ case InferenceMode.PREFER_ON_DEVICE:
2154
+ if (await chromeAdapter.isAvailable(request)) {
2155
+ return onDeviceCall();
2156
+ }
2157
+ return inCloudCall();
2158
+ default:
2159
+ throw new AIError(AIErrorCode.ERROR, `Unexpected infererence mode: ${chromeAdapter.mode}`);
2160
+ }
2161
+ }
2162
+
1737
2163
  /**
1738
2164
  * @license
1739
2165
  * Copyright 2024 Google LLC
@@ -1758,13 +2184,7 @@ async function generateContentStreamOnCloud(apiSettings, model, params, requestO
1758
2184
  /* stream */ true, JSON.stringify(params), requestOptions);
1759
2185
  }
1760
2186
  async function generateContentStream(apiSettings, model, params, chromeAdapter, requestOptions) {
1761
- let response;
1762
- if (chromeAdapter && (await chromeAdapter.isAvailable(params))) {
1763
- response = await chromeAdapter.generateContentStream(params);
1764
- }
1765
- else {
1766
- response = await generateContentStreamOnCloud(apiSettings, model, params, requestOptions);
1767
- }
2187
+ const response = await callCloudOrDevice(params, chromeAdapter, () => chromeAdapter.generateContentStream(params), () => generateContentStreamOnCloud(apiSettings, model, params, requestOptions));
1768
2188
  return processStream(response, apiSettings); // TODO: Map streaming responses
1769
2189
  }
1770
2190
  async function generateContentOnCloud(apiSettings, model, params, requestOptions) {
@@ -1775,13 +2195,7 @@ async function generateContentOnCloud(apiSettings, model, params, requestOptions
1775
2195
  /* stream */ false, JSON.stringify(params), requestOptions);
1776
2196
  }
1777
2197
  async function generateContent(apiSettings, model, params, chromeAdapter, requestOptions) {
1778
- let response;
1779
- if (chromeAdapter && (await chromeAdapter.isAvailable(params))) {
1780
- response = await chromeAdapter.generateContent(params);
1781
- }
1782
- else {
1783
- response = await generateContentOnCloud(apiSettings, model, params, requestOptions);
1784
- }
2198
+ const response = await callCloudOrDevice(params, chromeAdapter, () => chromeAdapter.generateContent(params), () => generateContentOnCloud(apiSettings, model, params, requestOptions));
1785
2199
  const generateContentResponse = await processGenerateContentResponse(response, apiSettings);
1786
2200
  const enhancedResponse = createEnhancedContentResponse(generateContentResponse);
1787
2201
  return {
@@ -1991,7 +2405,9 @@ function validateChatHistory(history) {
1991
2405
  functionCall: 0,
1992
2406
  functionResponse: 0,
1993
2407
  thought: 0,
1994
- thoughtSignature: 0
2408
+ thoughtSignature: 0,
2409
+ executableCode: 0,
2410
+ codeExecutionResult: 0
1995
2411
  };
1996
2412
  for (const part of parts) {
1997
2413
  for (const key of VALID_PART_FIELDS) {
@@ -2192,8 +2608,8 @@ async function countTokensOnCloud(apiSettings, model, params, requestOptions) {
2192
2608
  return response.json();
2193
2609
  }
2194
2610
  async function countTokens(apiSettings, model, params, chromeAdapter, requestOptions) {
2195
- if (chromeAdapter && (await chromeAdapter.isAvailable(params))) {
2196
- return (await chromeAdapter.countTokens(params)).json();
2611
+ if (chromeAdapter?.mode === InferenceMode.ONLY_ON_DEVICE) {
2612
+ throw new AIError(AIErrorCode.UNSUPPORTED, 'countTokens() is not supported for on-device models.');
2197
2613
  }
2198
2614
  return countTokensOnCloud(apiSettings, model, params, requestOptions);
2199
2615
  }
@@ -3607,316 +4023,10 @@ function getLiveGenerativeModel(ai, modelParams) {
3607
4023
  }
3608
4024
 
3609
4025
  /**
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
4026
+ * The Firebase AI Web SDK.
3629
4027
  *
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.
4028
+ * @packageDocumentation
3640
4029
  */
3641
- class ChromeAdapterImpl {
3642
- constructor(languageModelProvider, mode, onDeviceParams = {
3643
- createOptions: {
3644
- // Defaults to support image inputs for convenience.
3645
- expectedInputs: [{ type: 'image' }]
3646
- }
3647
- }) {
3648
- this.languageModelProvider = languageModelProvider;
3649
- this.mode = mode;
3650
- this.onDeviceParams = onDeviceParams;
3651
- this.isDownloading = false;
3652
- }
3653
- /**
3654
- * Checks if a given request can be made on-device.
3655
- *
3656
- * Encapsulates a few concerns:
3657
- * the mode
3658
- * API existence
3659
- * prompt formatting
3660
- * model availability, including triggering download if necessary
3661
- *
3662
- *
3663
- * Pros: callers needn't be concerned with details of on-device availability.</p>
3664
- * Cons: this method spans a few concerns and splits request validation from usage.
3665
- * If instance variables weren't already part of the API, we could consider a better
3666
- * separation of concerns.
3667
- */
3668
- async isAvailable(request) {
3669
- if (!this.mode) {
3670
- logger.debug(`On-device inference unavailable because mode is undefined.`);
3671
- return false;
3672
- }
3673
- if (this.mode === InferenceMode.ONLY_IN_CLOUD) {
3674
- logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
3675
- return false;
3676
- }
3677
- // Triggers out-of-band download so model will eventually become available.
3678
- const availability = await this.downloadIfAvailable();
3679
- if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
3680
- // If it will never be available due to API inavailability, throw.
3681
- if (availability === Availability.UNAVAILABLE) {
3682
- throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
3683
- }
3684
- else if (availability === Availability.DOWNLOADABLE ||
3685
- availability === Availability.DOWNLOADING) {
3686
- // TODO(chholland): Better user experience during download - progress?
3687
- logger.debug(`Waiting for download of LanguageModel to complete.`);
3688
- await this.downloadPromise;
3689
- return true;
3690
- }
3691
- return true;
3692
- }
3693
- // Applies prefer_on_device logic.
3694
- if (availability !== Availability.AVAILABLE) {
3695
- logger.debug(`On-device inference unavailable because availability is "${availability}".`);
3696
- return false;
3697
- }
3698
- if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
3699
- logger.debug(`On-device inference unavailable because request is incompatible.`);
3700
- return false;
3701
- }
3702
- return true;
3703
- }
3704
- /**
3705
- * Generates content on device.
3706
- *
3707
- * @remarks
3708
- * This is comparable to {@link GenerativeModel.generateContent} for generating content in
3709
- * Cloud.
3710
- * @param request - a standard Firebase AI {@link GenerateContentRequest}
3711
- * @returns {@link Response}, so we can reuse common response formatting.
3712
- */
3713
- async generateContent(request) {
3714
- const session = await this.createSession();
3715
- const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
3716
- const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
3717
- return ChromeAdapterImpl.toResponse(text);
3718
- }
3719
- /**
3720
- * Generates content stream on device.
3721
- *
3722
- * @remarks
3723
- * This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
3724
- * Cloud.
3725
- * @param request - a standard Firebase AI {@link GenerateContentRequest}
3726
- * @returns {@link Response}, so we can reuse common response formatting.
3727
- */
3728
- async generateContentStream(request) {
3729
- const session = await this.createSession();
3730
- const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
3731
- const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
3732
- return ChromeAdapterImpl.toStreamResponse(stream);
3733
- }
3734
- async countTokens(_request) {
3735
- throw new AIError(AIErrorCode.REQUEST_ERROR, 'Count Tokens is not yet available for on-device model.');
3736
- }
3737
- /**
3738
- * Asserts inference for the given request can be performed by an on-device model.
3739
- */
3740
- static isOnDeviceRequest(request) {
3741
- // Returns false if the prompt is empty.
3742
- if (request.contents.length === 0) {
3743
- logger.debug('Empty prompt rejected for on-device inference.');
3744
- return false;
3745
- }
3746
- for (const content of request.contents) {
3747
- if (content.role === 'function') {
3748
- logger.debug(`"Function" role rejected for on-device inference.`);
3749
- return false;
3750
- }
3751
- // Returns false if request contains an image with an unsupported mime type.
3752
- for (const part of content.parts) {
3753
- if (part.inlineData &&
3754
- ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
3755
- logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
3756
- return false;
3757
- }
3758
- }
3759
- }
3760
- return true;
3761
- }
3762
- /**
3763
- * Encapsulates logic to get availability and download a model if one is downloadable.
3764
- */
3765
- async downloadIfAvailable() {
3766
- const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
3767
- if (availability === Availability.DOWNLOADABLE) {
3768
- this.download();
3769
- }
3770
- return availability;
3771
- }
3772
- /**
3773
- * Triggers out-of-band download of an on-device model.
3774
- *
3775
- * Chrome only downloads models as needed. Chrome knows a model is needed when code calls
3776
- * LanguageModel.create.
3777
- *
3778
- * Since Chrome manages the download, the SDK can only avoid redundant download requests by
3779
- * tracking if a download has previously been requested.
3780
- */
3781
- download() {
3782
- if (this.isDownloading) {
3783
- return;
3784
- }
3785
- this.isDownloading = true;
3786
- this.downloadPromise = this.languageModelProvider
3787
- ?.create(this.onDeviceParams.createOptions)
3788
- .finally(() => {
3789
- this.isDownloading = false;
3790
- });
3791
- }
3792
- /**
3793
- * Converts Firebase AI {@link Content} object to a Chrome {@link LanguageModelMessage} object.
3794
- */
3795
- static async toLanguageModelMessage(content) {
3796
- const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
3797
- return {
3798
- role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
3799
- content: languageModelMessageContents
3800
- };
3801
- }
3802
- /**
3803
- * Converts a Firebase AI Part object to a Chrome LanguageModelMessageContent object.
3804
- */
3805
- static async toLanguageModelMessageContent(part) {
3806
- if (part.text) {
3807
- return {
3808
- type: 'text',
3809
- value: part.text
3810
- };
3811
- }
3812
- else if (part.inlineData) {
3813
- const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
3814
- const imageBlob = await formattedImageContent.blob();
3815
- const imageBitmap = await createImageBitmap(imageBlob);
3816
- return {
3817
- type: 'image',
3818
- value: imageBitmap
3819
- };
3820
- }
3821
- throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
3822
- }
3823
- /**
3824
- * Converts a Firebase AI {@link Role} string to a {@link LanguageModelMessageRole} string.
3825
- */
3826
- static toLanguageModelMessageRole(role) {
3827
- // Assumes 'function' rule has been filtered by isOnDeviceRequest
3828
- return role === 'model' ? 'assistant' : 'user';
3829
- }
3830
- /**
3831
- * Abstracts Chrome session creation.
3832
- *
3833
- * Chrome uses a multi-turn session for all inference. Firebase AI uses single-turn for all
3834
- * inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
3835
- * inference.
3836
- *
3837
- * Chrome will remove a model from memory if it's no longer in use, so this method ensures a
3838
- * new session is created before an old session is destroyed.
3839
- */
3840
- async createSession() {
3841
- if (!this.languageModelProvider) {
3842
- throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
3843
- }
3844
- const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
3845
- if (this.oldSession) {
3846
- this.oldSession.destroy();
3847
- }
3848
- // Holds session reference, so model isn't unloaded from memory.
3849
- this.oldSession = newSession;
3850
- return newSession;
3851
- }
3852
- /**
3853
- * Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
3854
- */
3855
- static toResponse(text) {
3856
- return {
3857
- json: async () => ({
3858
- candidates: [
3859
- {
3860
- content: {
3861
- parts: [{ text }]
3862
- }
3863
- }
3864
- ]
3865
- })
3866
- };
3867
- }
3868
- /**
3869
- * Formats string stream returned by Chrome as SSE returned by Firebase AI.
3870
- */
3871
- static toStreamResponse(stream) {
3872
- const encoder = new TextEncoder();
3873
- return {
3874
- body: stream.pipeThrough(new TransformStream({
3875
- transform(chunk, controller) {
3876
- const json = JSON.stringify({
3877
- candidates: [
3878
- {
3879
- content: {
3880
- role: 'model',
3881
- parts: [{ text: chunk }]
3882
- }
3883
- }
3884
- ]
3885
- });
3886
- controller.enqueue(encoder.encode(`data: ${json}\n\n`));
3887
- }
3888
- }))
3889
- };
3890
- }
3891
- }
3892
- // Visible for testing
3893
- ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
3894
- /**
3895
- * Creates a ChromeAdapterImpl on demand.
3896
- */
3897
- function chromeAdapterFactory(mode, window, params) {
3898
- // Do not initialize a ChromeAdapter if we are not in hybrid mode.
3899
- if (typeof window !== 'undefined' && mode) {
3900
- return new ChromeAdapterImpl(window.LanguageModel, mode, params);
3901
- }
3902
- }
3903
-
3904
- /**
3905
- * The Firebase AI Web SDK.
3906
- *
3907
- * @packageDocumentation
3908
- */
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
4030
  function registerAI() {
3921
4031
  _registerComponent(new Component(AI_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
3922
4032
  registerVersion(name, version);
@@ -3925,5 +4035,5 @@ function registerAI() {
3925
4035
  }
3926
4036
  registerAI();
3927
4037
 
3928
- export { AIError, AIErrorCode, AIModel, AnyOfSchema, ArraySchema, Backend, BackendType, BlockReason, BooleanSchema, ChatSession, FinishReason, FunctionCallingMode, GenerativeModel, GoogleAIBackend, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, ImagenAspectRatio, ImagenImageFormat, ImagenModel, ImagenPersonFilterLevel, ImagenSafetyFilterLevel, InferenceMode, IntegerSchema, LiveGenerativeModel, LiveResponseType, LiveSession, Modality, NumberSchema, ObjectSchema, POSSIBLE_ROLES, ResponseModality, Schema, SchemaType, StringSchema, VertexAIBackend, getAI, getGenerativeModel, getImagenModel, getLiveGenerativeModel, startAudioConversation };
4038
+ export { AIError, AIErrorCode, AIModel, AnyOfSchema, ArraySchema, Backend, BackendType, BlockReason, BooleanSchema, ChatSession, FinishReason, FunctionCallingMode, GenerativeModel, GoogleAIBackend, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, ImagenAspectRatio, ImagenImageFormat, ImagenModel, ImagenPersonFilterLevel, ImagenSafetyFilterLevel, InferenceMode, IntegerSchema, Language, LiveGenerativeModel, LiveResponseType, LiveSession, Modality, NumberSchema, ObjectSchema, Outcome, POSSIBLE_ROLES, ResponseModality, Schema, SchemaType, StringSchema, VertexAIBackend, getAI, getGenerativeModel, getImagenModel, getLiveGenerativeModel, startAudioConversation };
3929
4039
  //# sourceMappingURL=index.esm.js.map