@firebase/ai 0.0.1

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.
Files changed (90) hide show
  1. package/README.md +5 -0
  2. package/dist/ai-public.d.ts +1972 -0
  3. package/dist/ai.d.ts +2073 -0
  4. package/dist/esm/index.esm2017.js +2624 -0
  5. package/dist/esm/index.esm2017.js.map +1 -0
  6. package/dist/esm/package.json +1 -0
  7. package/dist/esm/src/api.d.ts +120 -0
  8. package/dist/esm/src/backend.d.ts +74 -0
  9. package/dist/esm/src/constants.d.ts +23 -0
  10. package/dist/esm/src/errors.d.ts +35 -0
  11. package/dist/esm/src/googleai-mappers.d.ts +73 -0
  12. package/dist/esm/src/helpers.d.ts +30 -0
  13. package/dist/esm/src/index.d.ts +12 -0
  14. package/dist/esm/src/index.node.d.ts +7 -0
  15. package/dist/esm/src/logger.d.ts +18 -0
  16. package/dist/esm/src/methods/chat-session-helpers.d.ts +18 -0
  17. package/dist/esm/src/methods/chat-session.d.ts +50 -0
  18. package/dist/esm/src/methods/count-tokens.d.ts +19 -0
  19. package/dist/esm/src/methods/generate-content.d.ts +20 -0
  20. package/dist/esm/src/models/ai-model.d.ts +72 -0
  21. package/dist/esm/src/models/generative-model.d.ts +54 -0
  22. package/dist/esm/src/models/imagen-model.d.ts +102 -0
  23. package/dist/esm/src/models/index.d.ts +19 -0
  24. package/dist/esm/src/public-types.d.ts +106 -0
  25. package/dist/esm/src/requests/imagen-image-format.d.ts +61 -0
  26. package/dist/esm/src/requests/request-helpers.d.ts +28 -0
  27. package/dist/esm/src/requests/request.d.ts +43 -0
  28. package/dist/esm/src/requests/response-helpers.d.ts +53 -0
  29. package/dist/esm/src/requests/schema-builder.d.ts +145 -0
  30. package/dist/esm/src/requests/stream-reader.d.ts +38 -0
  31. package/dist/esm/src/service.d.ts +31 -0
  32. package/dist/esm/src/types/content.d.ts +144 -0
  33. package/dist/esm/src/types/enums.d.ts +263 -0
  34. package/dist/esm/src/types/error.d.ts +81 -0
  35. package/dist/esm/src/types/googleai.d.ts +56 -0
  36. package/dist/esm/src/types/imagen/index.d.ts +18 -0
  37. package/dist/esm/src/types/imagen/internal.d.ts +124 -0
  38. package/dist/esm/src/types/imagen/requests.d.ts +211 -0
  39. package/dist/esm/src/types/imagen/responses.d.ts +78 -0
  40. package/dist/esm/src/types/index.d.ts +24 -0
  41. package/dist/esm/src/types/internal.d.ts +33 -0
  42. package/dist/esm/src/types/requests.d.ts +213 -0
  43. package/dist/esm/src/types/responses.d.ts +257 -0
  44. package/dist/esm/src/types/schema.d.ts +102 -0
  45. package/dist/index.cjs.js +2652 -0
  46. package/dist/index.cjs.js.map +1 -0
  47. package/dist/index.node.cjs.js +2652 -0
  48. package/dist/index.node.cjs.js.map +1 -0
  49. package/dist/index.node.mjs +2624 -0
  50. package/dist/index.node.mjs.map +1 -0
  51. package/dist/src/api.d.ts +120 -0
  52. package/dist/src/backend.d.ts +74 -0
  53. package/dist/src/constants.d.ts +23 -0
  54. package/dist/src/errors.d.ts +35 -0
  55. package/dist/src/googleai-mappers.d.ts +73 -0
  56. package/dist/src/helpers.d.ts +30 -0
  57. package/dist/src/index.d.ts +12 -0
  58. package/dist/src/index.node.d.ts +7 -0
  59. package/dist/src/logger.d.ts +18 -0
  60. package/dist/src/methods/chat-session-helpers.d.ts +18 -0
  61. package/dist/src/methods/chat-session.d.ts +50 -0
  62. package/dist/src/methods/count-tokens.d.ts +19 -0
  63. package/dist/src/methods/generate-content.d.ts +20 -0
  64. package/dist/src/models/ai-model.d.ts +72 -0
  65. package/dist/src/models/generative-model.d.ts +54 -0
  66. package/dist/src/models/imagen-model.d.ts +102 -0
  67. package/dist/src/models/index.d.ts +19 -0
  68. package/dist/src/public-types.d.ts +106 -0
  69. package/dist/src/requests/imagen-image-format.d.ts +61 -0
  70. package/dist/src/requests/request-helpers.d.ts +28 -0
  71. package/dist/src/requests/request.d.ts +43 -0
  72. package/dist/src/requests/response-helpers.d.ts +53 -0
  73. package/dist/src/requests/schema-builder.d.ts +145 -0
  74. package/dist/src/requests/stream-reader.d.ts +38 -0
  75. package/dist/src/service.d.ts +31 -0
  76. package/dist/src/tsdoc-metadata.json +11 -0
  77. package/dist/src/types/content.d.ts +144 -0
  78. package/dist/src/types/enums.d.ts +263 -0
  79. package/dist/src/types/error.d.ts +81 -0
  80. package/dist/src/types/googleai.d.ts +56 -0
  81. package/dist/src/types/imagen/index.d.ts +18 -0
  82. package/dist/src/types/imagen/internal.d.ts +124 -0
  83. package/dist/src/types/imagen/requests.d.ts +211 -0
  84. package/dist/src/types/imagen/responses.d.ts +78 -0
  85. package/dist/src/types/index.d.ts +24 -0
  86. package/dist/src/types/internal.d.ts +33 -0
  87. package/dist/src/types/requests.d.ts +213 -0
  88. package/dist/src/types/responses.d.ts +257 -0
  89. package/dist/src/types/schema.d.ts +102 -0
  90. package/package.json +81 -0
@@ -0,0 +1,2624 @@
1
+ import { _isFirebaseServerApp, _getProvider, getApp, _registerComponent, registerVersion } from '@firebase/app';
2
+ import { Component } from '@firebase/component';
3
+ import { FirebaseError, getModularInstance } from '@firebase/util';
4
+ import { Logger } from '@firebase/logger';
5
+ import { __asyncGenerator, __await } from 'tslib';
6
+
7
+ var name = "@firebase/ai";
8
+ var version = "1.2.2";
9
+
10
+ /**
11
+ * @license
12
+ * Copyright 2024 Google LLC
13
+ *
14
+ * Licensed under the Apache License, Version 2.0 (the "License");
15
+ * you may not use this file except in compliance with the License.
16
+ * You may obtain a copy of the License at
17
+ *
18
+ * http://www.apache.org/licenses/LICENSE-2.0
19
+ *
20
+ * Unless required by applicable law or agreed to in writing, software
21
+ * distributed under the License is distributed on an "AS IS" BASIS,
22
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ * See the License for the specific language governing permissions and
24
+ * limitations under the License.
25
+ */
26
+ const AI_TYPE = 'AI';
27
+ const DEFAULT_LOCATION = 'us-central1';
28
+ const DEFAULT_BASE_URL = 'https://firebasevertexai.googleapis.com';
29
+ const DEFAULT_API_VERSION = 'v1beta';
30
+ const PACKAGE_VERSION = version;
31
+ const LANGUAGE_TAG = 'gl-js';
32
+ const DEFAULT_FETCH_TIMEOUT_MS = 180 * 1000;
33
+
34
+ /**
35
+ * @license
36
+ * Copyright 2024 Google LLC
37
+ *
38
+ * Licensed under the Apache License, Version 2.0 (the "License");
39
+ * you may not use this file except in compliance with the License.
40
+ * You may obtain a copy of the License at
41
+ *
42
+ * http://www.apache.org/licenses/LICENSE-2.0
43
+ *
44
+ * Unless required by applicable law or agreed to in writing, software
45
+ * distributed under the License is distributed on an "AS IS" BASIS,
46
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
47
+ * See the License for the specific language governing permissions and
48
+ * limitations under the License.
49
+ */
50
+ /**
51
+ * Possible roles.
52
+ * @public
53
+ */
54
+ const POSSIBLE_ROLES = ['user', 'model', 'function', 'system'];
55
+ /**
56
+ * Harm categories that would cause prompts or candidates to be blocked.
57
+ * @public
58
+ */
59
+ var HarmCategory;
60
+ (function (HarmCategory) {
61
+ HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
62
+ HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
63
+ HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
64
+ HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
65
+ })(HarmCategory || (HarmCategory = {}));
66
+ /**
67
+ * Threshold above which a prompt or candidate will be blocked.
68
+ * @public
69
+ */
70
+ var HarmBlockThreshold;
71
+ (function (HarmBlockThreshold) {
72
+ /**
73
+ * Content with `NEGLIGIBLE` will be allowed.
74
+ */
75
+ HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
76
+ /**
77
+ * Content with `NEGLIGIBLE` and `LOW` will be allowed.
78
+ */
79
+ HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
80
+ /**
81
+ * Content with `NEGLIGIBLE`, `LOW`, and `MEDIUM` will be allowed.
82
+ */
83
+ HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
84
+ /**
85
+ * All content will be allowed.
86
+ */
87
+ HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE";
88
+ })(HarmBlockThreshold || (HarmBlockThreshold = {}));
89
+ /**
90
+ * This property is not supported in the Gemini Developer API ({@link GoogleAIBackend}).
91
+ *
92
+ * @public
93
+ */
94
+ var HarmBlockMethod;
95
+ (function (HarmBlockMethod) {
96
+ /**
97
+ * The harm block method uses both probability and severity scores.
98
+ */
99
+ HarmBlockMethod["SEVERITY"] = "SEVERITY";
100
+ /**
101
+ * The harm block method uses the probability score.
102
+ */
103
+ HarmBlockMethod["PROBABILITY"] = "PROBABILITY";
104
+ })(HarmBlockMethod || (HarmBlockMethod = {}));
105
+ /**
106
+ * Probability that a prompt or candidate matches a harm category.
107
+ * @public
108
+ */
109
+ var HarmProbability;
110
+ (function (HarmProbability) {
111
+ /**
112
+ * Content has a negligible chance of being unsafe.
113
+ */
114
+ HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE";
115
+ /**
116
+ * Content has a low chance of being unsafe.
117
+ */
118
+ HarmProbability["LOW"] = "LOW";
119
+ /**
120
+ * Content has a medium chance of being unsafe.
121
+ */
122
+ HarmProbability["MEDIUM"] = "MEDIUM";
123
+ /**
124
+ * Content has a high chance of being unsafe.
125
+ */
126
+ HarmProbability["HIGH"] = "HIGH";
127
+ })(HarmProbability || (HarmProbability = {}));
128
+ /**
129
+ * Harm severity levels.
130
+ * @public
131
+ */
132
+ var HarmSeverity;
133
+ (function (HarmSeverity) {
134
+ /**
135
+ * Negligible level of harm severity.
136
+ */
137
+ HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE";
138
+ /**
139
+ * Low level of harm severity.
140
+ */
141
+ HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW";
142
+ /**
143
+ * Medium level of harm severity.
144
+ */
145
+ HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM";
146
+ /**
147
+ * High level of harm severity.
148
+ */
149
+ HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH";
150
+ /**
151
+ * Harm severity is not supported.
152
+ *
153
+ * @remarks
154
+ * The GoogleAI backend does not support `HarmSeverity`, so this value is used as a fallback.
155
+ */
156
+ HarmSeverity["HARM_SEVERITY_UNSUPPORTED"] = "HARM_SEVERITY_UNSUPPORTED";
157
+ })(HarmSeverity || (HarmSeverity = {}));
158
+ /**
159
+ * Reason that a prompt was blocked.
160
+ * @public
161
+ */
162
+ var BlockReason;
163
+ (function (BlockReason) {
164
+ /**
165
+ * Content was blocked by safety settings.
166
+ */
167
+ BlockReason["SAFETY"] = "SAFETY";
168
+ /**
169
+ * Content was blocked, but the reason is uncategorized.
170
+ */
171
+ BlockReason["OTHER"] = "OTHER";
172
+ /**
173
+ * Content was blocked because it contained terms from the terminology blocklist.
174
+ */
175
+ BlockReason["BLOCKLIST"] = "BLOCKLIST";
176
+ /**
177
+ * Content was blocked due to prohibited content.
178
+ */
179
+ BlockReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
180
+ })(BlockReason || (BlockReason = {}));
181
+ /**
182
+ * Reason that a candidate finished.
183
+ * @public
184
+ */
185
+ var FinishReason;
186
+ (function (FinishReason) {
187
+ /**
188
+ * Natural stop point of the model or provided stop sequence.
189
+ */
190
+ FinishReason["STOP"] = "STOP";
191
+ /**
192
+ * The maximum number of tokens as specified in the request was reached.
193
+ */
194
+ FinishReason["MAX_TOKENS"] = "MAX_TOKENS";
195
+ /**
196
+ * The candidate content was flagged for safety reasons.
197
+ */
198
+ FinishReason["SAFETY"] = "SAFETY";
199
+ /**
200
+ * The candidate content was flagged for recitation reasons.
201
+ */
202
+ FinishReason["RECITATION"] = "RECITATION";
203
+ /**
204
+ * Unknown reason.
205
+ */
206
+ FinishReason["OTHER"] = "OTHER";
207
+ /**
208
+ * The candidate content contained forbidden terms.
209
+ */
210
+ FinishReason["BLOCKLIST"] = "BLOCKLIST";
211
+ /**
212
+ * The candidate content potentially contained prohibited content.
213
+ */
214
+ FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
215
+ /**
216
+ * The candidate content potentially contained Sensitive Personally Identifiable Information (SPII).
217
+ */
218
+ FinishReason["SPII"] = "SPII";
219
+ /**
220
+ * The function call generated by the model was invalid.
221
+ */
222
+ FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
223
+ })(FinishReason || (FinishReason = {}));
224
+ /**
225
+ * @public
226
+ */
227
+ var FunctionCallingMode;
228
+ (function (FunctionCallingMode) {
229
+ /**
230
+ * Default model behavior; model decides to predict either a function call
231
+ * or a natural language response.
232
+ */
233
+ FunctionCallingMode["AUTO"] = "AUTO";
234
+ /**
235
+ * Model is constrained to always predicting a function call only.
236
+ * If `allowed_function_names` is set, the predicted function call will be
237
+ * limited to any one of `allowed_function_names`, else the predicted
238
+ * function call will be any one of the provided `function_declarations`.
239
+ */
240
+ FunctionCallingMode["ANY"] = "ANY";
241
+ /**
242
+ * Model will not predict any function call. Model behavior is same as when
243
+ * not passing any function declarations.
244
+ */
245
+ FunctionCallingMode["NONE"] = "NONE";
246
+ })(FunctionCallingMode || (FunctionCallingMode = {}));
247
+ /**
248
+ * Content part modality.
249
+ * @public
250
+ */
251
+ var Modality;
252
+ (function (Modality) {
253
+ /**
254
+ * Unspecified modality.
255
+ */
256
+ Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
257
+ /**
258
+ * Plain text.
259
+ */
260
+ Modality["TEXT"] = "TEXT";
261
+ /**
262
+ * Image.
263
+ */
264
+ Modality["IMAGE"] = "IMAGE";
265
+ /**
266
+ * Video.
267
+ */
268
+ Modality["VIDEO"] = "VIDEO";
269
+ /**
270
+ * Audio.
271
+ */
272
+ Modality["AUDIO"] = "AUDIO";
273
+ /**
274
+ * Document (for example, PDF).
275
+ */
276
+ Modality["DOCUMENT"] = "DOCUMENT";
277
+ })(Modality || (Modality = {}));
278
+ /**
279
+ * Generation modalities to be returned in generation responses.
280
+ *
281
+ * @beta
282
+ */
283
+ const ResponseModality = {
284
+ /**
285
+ * Text.
286
+ * @beta
287
+ */
288
+ TEXT: 'TEXT',
289
+ /**
290
+ * Image.
291
+ * @beta
292
+ */
293
+ IMAGE: 'IMAGE'
294
+ };
295
+
296
+ /**
297
+ * @license
298
+ * Copyright 2024 Google LLC
299
+ *
300
+ * Licensed under the Apache License, Version 2.0 (the "License");
301
+ * you may not use this file except in compliance with the License.
302
+ * You may obtain a copy of the License at
303
+ *
304
+ * http://www.apache.org/licenses/LICENSE-2.0
305
+ *
306
+ * Unless required by applicable law or agreed to in writing, software
307
+ * distributed under the License is distributed on an "AS IS" BASIS,
308
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
309
+ * See the License for the specific language governing permissions and
310
+ * limitations under the License.
311
+ */
312
+ /**
313
+ * Contains the list of OpenAPI data types
314
+ * as defined by the
315
+ * {@link https://swagger.io/docs/specification/data-models/data-types/ | OpenAPI specification}
316
+ * @public
317
+ */
318
+ var SchemaType;
319
+ (function (SchemaType) {
320
+ /** String type. */
321
+ SchemaType["STRING"] = "string";
322
+ /** Number type. */
323
+ SchemaType["NUMBER"] = "number";
324
+ /** Integer type. */
325
+ SchemaType["INTEGER"] = "integer";
326
+ /** Boolean type. */
327
+ SchemaType["BOOLEAN"] = "boolean";
328
+ /** Array type. */
329
+ SchemaType["ARRAY"] = "array";
330
+ /** Object type. */
331
+ SchemaType["OBJECT"] = "object";
332
+ })(SchemaType || (SchemaType = {}));
333
+
334
+ /**
335
+ * @license
336
+ * Copyright 2025 Google LLC
337
+ *
338
+ * Licensed under the Apache License, Version 2.0 (the "License");
339
+ * you may not use this file except in compliance with the License.
340
+ * You may obtain a copy of the License at
341
+ *
342
+ * http://www.apache.org/licenses/LICENSE-2.0
343
+ *
344
+ * Unless required by applicable law or agreed to in writing, software
345
+ * distributed under the License is distributed on an "AS IS" BASIS,
346
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
347
+ * See the License for the specific language governing permissions and
348
+ * limitations under the License.
349
+ */
350
+ /**
351
+ * A filter level controlling how aggressively to filter sensitive content.
352
+ *
353
+ * Text prompts provided as inputs and images (generated or uploaded) through Imagen on Vertex AI
354
+ * are assessed against a list of safety filters, which include 'harmful categories' (for example,
355
+ * `violence`, `sexual`, `derogatory`, and `toxic`). This filter level controls how aggressively to
356
+ * filter out potentially harmful content from responses. See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation }
357
+ * and the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#safety-filters | Responsible AI and usage guidelines}
358
+ * for more details.
359
+ *
360
+ * @beta
361
+ */
362
+ var ImagenSafetyFilterLevel;
363
+ (function (ImagenSafetyFilterLevel) {
364
+ /**
365
+ * The most aggressive filtering level; most strict blocking.
366
+ */
367
+ ImagenSafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "block_low_and_above";
368
+ /**
369
+ * Blocks some sensitive prompts and responses.
370
+ */
371
+ ImagenSafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "block_medium_and_above";
372
+ /**
373
+ * Blocks few sensitive prompts and responses.
374
+ */
375
+ ImagenSafetyFilterLevel["BLOCK_ONLY_HIGH"] = "block_only_high";
376
+ /**
377
+ * The least aggressive filtering level; blocks very few sensitive prompts and responses.
378
+ *
379
+ * Access to this feature is restricted and may require your case to be reviewed and approved by
380
+ * Cloud support.
381
+ */
382
+ ImagenSafetyFilterLevel["BLOCK_NONE"] = "block_none";
383
+ })(ImagenSafetyFilterLevel || (ImagenSafetyFilterLevel = {}));
384
+ /**
385
+ * A filter level controlling whether generation of images containing people or faces is allowed.
386
+ *
387
+ * See the <a href="http://firebase.google.com/docs/vertex-ai/generate-images">personGeneration</a>
388
+ * documentation for more details.
389
+ *
390
+ * @beta
391
+ */
392
+ var ImagenPersonFilterLevel;
393
+ (function (ImagenPersonFilterLevel) {
394
+ /**
395
+ * Disallow generation of images containing people or faces; images of people are filtered out.
396
+ */
397
+ ImagenPersonFilterLevel["BLOCK_ALL"] = "dont_allow";
398
+ /**
399
+ * Allow generation of images containing adults only; images of children are filtered out.
400
+ *
401
+ * Generation of images containing people or faces may require your use case to be
402
+ * reviewed and approved by Cloud support; see the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#person-face-gen | Responsible AI and usage guidelines}
403
+ * for more details.
404
+ */
405
+ ImagenPersonFilterLevel["ALLOW_ADULT"] = "allow_adult";
406
+ /**
407
+ * Allow generation of images containing adults only; images of children are filtered out.
408
+ *
409
+ * Generation of images containing people or faces may require your use case to be
410
+ * reviewed and approved by Cloud support; see the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#person-face-gen | Responsible AI and usage guidelines}
411
+ * for more details.
412
+ */
413
+ ImagenPersonFilterLevel["ALLOW_ALL"] = "allow_all";
414
+ })(ImagenPersonFilterLevel || (ImagenPersonFilterLevel = {}));
415
+ /**
416
+ * Aspect ratios for Imagen images.
417
+ *
418
+ * To specify an aspect ratio for generated images, set the `aspectRatio` property in your
419
+ * {@link ImagenGenerationConfig}.
420
+ *
421
+ * See the the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation }
422
+ * for more details and examples of the supported aspect ratios.
423
+ *
424
+ * @beta
425
+ */
426
+ var ImagenAspectRatio;
427
+ (function (ImagenAspectRatio) {
428
+ /**
429
+ * Square (1:1) aspect ratio.
430
+ */
431
+ ImagenAspectRatio["SQUARE"] = "1:1";
432
+ /**
433
+ * Landscape (3:4) aspect ratio.
434
+ */
435
+ ImagenAspectRatio["LANDSCAPE_3x4"] = "3:4";
436
+ /**
437
+ * Portrait (4:3) aspect ratio.
438
+ */
439
+ ImagenAspectRatio["PORTRAIT_4x3"] = "4:3";
440
+ /**
441
+ * Landscape (16:9) aspect ratio.
442
+ */
443
+ ImagenAspectRatio["LANDSCAPE_16x9"] = "16:9";
444
+ /**
445
+ * Portrait (9:16) aspect ratio.
446
+ */
447
+ ImagenAspectRatio["PORTRAIT_9x16"] = "9:16";
448
+ })(ImagenAspectRatio || (ImagenAspectRatio = {}));
449
+
450
+ /**
451
+ * @license
452
+ * Copyright 2024 Google LLC
453
+ *
454
+ * Licensed under the Apache License, Version 2.0 (the "License");
455
+ * you may not use this file except in compliance with the License.
456
+ * You may obtain a copy of the License at
457
+ *
458
+ * http://www.apache.org/licenses/LICENSE-2.0
459
+ *
460
+ * Unless required by applicable law or agreed to in writing, software
461
+ * distributed under the License is distributed on an "AS IS" BASIS,
462
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
463
+ * See the License for the specific language governing permissions and
464
+ * limitations under the License.
465
+ */
466
+ /**
467
+ * An enum-like object containing constants that represent the supported backends
468
+ * for the Firebase AI SDK.
469
+ * This determines which backend service (Vertex AI Gemini API or Gemini Developer API)
470
+ * the SDK will communicate with.
471
+ *
472
+ * These values are assigned to the `backendType` property within the specific backend
473
+ * configuration objects ({@link GoogleAIBackend} or {@link VertexAIBackend}) to identify
474
+ * which service to target.
475
+ *
476
+ * @public
477
+ */
478
+ const BackendType = {
479
+ /**
480
+ * Identifies the backend service for the Vertex AI Gemini API provided through Google Cloud.
481
+ * Use this constant when creating a {@link VertexAIBackend} configuration.
482
+ */
483
+ VERTEX_AI: 'VERTEX_AI',
484
+ /**
485
+ * Identifies the backend service for the Gemini Developer API ({@link https://ai.google/ | Google AI}).
486
+ * Use this constant when creating a {@link GoogleAIBackend} configuration.
487
+ */
488
+ GOOGLE_AI: 'GOOGLE_AI'
489
+ }; // Using 'as const' makes the string values literal types
490
+
491
+ /**
492
+ * @license
493
+ * Copyright 2025 Google LLC
494
+ *
495
+ * Licensed under the Apache License, Version 2.0 (the "License");
496
+ * you may not use this file except in compliance with the License.
497
+ * You may obtain a copy of the License at
498
+ *
499
+ * http://www.apache.org/licenses/LICENSE-2.0
500
+ *
501
+ * Unless required by applicable law or agreed to in writing, software
502
+ * distributed under the License is distributed on an "AS IS" BASIS,
503
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
504
+ * See the License for the specific language governing permissions and
505
+ * limitations under the License.
506
+ */
507
+ /**
508
+ * Abstract base class representing the configuration for an AI service backend.
509
+ * This class should not be instantiated directly. Use its subclasses; {@link GoogleAIBackend} for
510
+ * the Gemini Developer API (via {@link https://ai.google/ | Google AI}), and
511
+ * {@link VertexAIBackend} for the Vertex AI Gemini API.
512
+ *
513
+ * @public
514
+ */
515
+ class Backend {
516
+ /**
517
+ * Protected constructor for use by subclasses.
518
+ * @param type - The backend type.
519
+ */
520
+ constructor(type) {
521
+ this.backendType = type;
522
+ }
523
+ }
524
+ /**
525
+ * Configuration class for the Gemini Developer API.
526
+ *
527
+ * Use this with {@link AIOptions} when initializing the AI service via
528
+ * {@link getAI | getAI()} to specify the Gemini Developer API as the backend.
529
+ *
530
+ * @public
531
+ */
532
+ class GoogleAIBackend extends Backend {
533
+ /**
534
+ * Creates a configuration object for the Gemini Developer API backend.
535
+ */
536
+ constructor() {
537
+ super(BackendType.GOOGLE_AI);
538
+ }
539
+ }
540
+ /**
541
+ * Configuration class for the Vertex AI Gemini API.
542
+ *
543
+ * Use this with {@link AIOptions} when initializing the AI service via
544
+ * {@link getAI | getAI()} to specify the Vertex AI Gemini API as the backend.
545
+ *
546
+ * @public
547
+ */
548
+ class VertexAIBackend extends Backend {
549
+ /**
550
+ * Creates a configuration object for the Vertex AI backend.
551
+ *
552
+ * @param location - The region identifier, defaulting to `us-central1`;
553
+ * see {@link https://firebase.google.com/docs/vertex-ai/locations#available-locations | Vertex AI locations}
554
+ * for a list of supported locations.
555
+ */
556
+ constructor(location = DEFAULT_LOCATION) {
557
+ super(BackendType.VERTEX_AI);
558
+ if (!location) {
559
+ this.location = DEFAULT_LOCATION;
560
+ }
561
+ else {
562
+ this.location = location;
563
+ }
564
+ }
565
+ }
566
+
567
+ /**
568
+ * @license
569
+ * Copyright 2024 Google LLC
570
+ *
571
+ * Licensed under the Apache License, Version 2.0 (the "License");
572
+ * you may not use this file except in compliance with the License.
573
+ * You may obtain a copy of the License at
574
+ *
575
+ * http://www.apache.org/licenses/LICENSE-2.0
576
+ *
577
+ * Unless required by applicable law or agreed to in writing, software
578
+ * distributed under the License is distributed on an "AS IS" BASIS,
579
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
580
+ * See the License for the specific language governing permissions and
581
+ * limitations under the License.
582
+ */
583
+ class AIService {
584
+ constructor(app, backend, authProvider, appCheckProvider) {
585
+ this.app = app;
586
+ this.backend = backend;
587
+ const appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
588
+ const auth = authProvider === null || authProvider === void 0 ? void 0 : authProvider.getImmediate({ optional: true });
589
+ this.auth = auth || null;
590
+ this.appCheck = appCheck || null;
591
+ if (backend instanceof VertexAIBackend) {
592
+ this.location = backend.location;
593
+ }
594
+ else {
595
+ this.location = '';
596
+ }
597
+ }
598
+ _delete() {
599
+ return Promise.resolve();
600
+ }
601
+ }
602
+
603
+ /**
604
+ * @license
605
+ * Copyright 2024 Google LLC
606
+ *
607
+ * Licensed under the Apache License, Version 2.0 (the "License");
608
+ * you may not use this file except in compliance with the License.
609
+ * You may obtain a copy of the License at
610
+ *
611
+ * http://www.apache.org/licenses/LICENSE-2.0
612
+ *
613
+ * Unless required by applicable law or agreed to in writing, software
614
+ * distributed under the License is distributed on an "AS IS" BASIS,
615
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
616
+ * See the License for the specific language governing permissions and
617
+ * limitations under the License.
618
+ */
619
+ /**
620
+ * Error class for the Firebase AI SDK.
621
+ *
622
+ * @public
623
+ */
624
+ class AIError extends FirebaseError {
625
+ /**
626
+ * Constructs a new instance of the `AIError` class.
627
+ *
628
+ * @param code - The error code from {@link AIErrorCode}.
629
+ * @param message - A human-readable message describing the error.
630
+ * @param customErrorData - Optional error data.
631
+ */
632
+ constructor(code, message, customErrorData) {
633
+ // Match error format used by FirebaseError from ErrorFactory
634
+ const service = AI_TYPE;
635
+ const fullCode = `${service}/${code}`;
636
+ const fullMessage = `${service}: ${message} (${fullCode})`;
637
+ super(code, fullMessage);
638
+ this.code = code;
639
+ this.customErrorData = customErrorData;
640
+ // FirebaseError initializes a stack trace, but it assumes the error is created from the error
641
+ // factory. Since we break this assumption, we set the stack trace to be originating from this
642
+ // constructor.
643
+ // This is only supported in V8.
644
+ if (Error.captureStackTrace) {
645
+ // Allows us to initialize the stack trace without including the constructor itself at the
646
+ // top level of the stack trace.
647
+ Error.captureStackTrace(this, AIError);
648
+ }
649
+ // Allows instanceof AIError in ES5/ES6
650
+ // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
651
+ // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
652
+ // which we can now use since we no longer target ES5.
653
+ Object.setPrototypeOf(this, AIError.prototype);
654
+ // Since Error is an interface, we don't inherit toString and so we define it ourselves.
655
+ this.toString = () => fullMessage;
656
+ }
657
+ }
658
+
659
+ /**
660
+ * @license
661
+ * Copyright 2025 Google LLC
662
+ *
663
+ * Licensed under the Apache License, Version 2.0 (the "License");
664
+ * you may not use this file except in compliance with the License.
665
+ * You may obtain a copy of the License at
666
+ *
667
+ * http://www.apache.org/licenses/LICENSE-2.0
668
+ *
669
+ * Unless required by applicable law or agreed to in writing, software
670
+ * distributed under the License is distributed on an "AS IS" BASIS,
671
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
672
+ * See the License for the specific language governing permissions and
673
+ * limitations under the License.
674
+ */
675
+ /**
676
+ * Encodes a {@link Backend} into a string that will be used to uniquely identify {@link AI}
677
+ * instances by backend type.
678
+ *
679
+ * @internal
680
+ */
681
+ function encodeInstanceIdentifier(backend) {
682
+ if (backend instanceof GoogleAIBackend) {
683
+ return `${AI_TYPE}/googleai`;
684
+ }
685
+ else if (backend instanceof VertexAIBackend) {
686
+ return `${AI_TYPE}/vertexai/${backend.location}`;
687
+ }
688
+ else {
689
+ throw new AIError("error" /* AIErrorCode.ERROR */, `Invalid backend: ${JSON.stringify(backend.backendType)}`);
690
+ }
691
+ }
692
+ /**
693
+ * Decodes an instance identifier string into a {@link Backend}.
694
+ *
695
+ * @internal
696
+ */
697
+ function decodeInstanceIdentifier(instanceIdentifier) {
698
+ const identifierParts = instanceIdentifier.split('/');
699
+ if (identifierParts[0] !== AI_TYPE) {
700
+ throw new AIError("error" /* AIErrorCode.ERROR */, `Invalid instance identifier, unknown prefix '${identifierParts[0]}'`);
701
+ }
702
+ const backendType = identifierParts[1];
703
+ switch (backendType) {
704
+ case 'vertexai':
705
+ const location = identifierParts[2];
706
+ if (!location) {
707
+ throw new AIError("error" /* AIErrorCode.ERROR */, `Invalid instance identifier, unknown location '${instanceIdentifier}'`);
708
+ }
709
+ return new VertexAIBackend(location);
710
+ case 'googleai':
711
+ return new GoogleAIBackend();
712
+ default:
713
+ throw new AIError("error" /* AIErrorCode.ERROR */, `Invalid instance identifier string: '${instanceIdentifier}'`);
714
+ }
715
+ }
716
+
717
+ /**
718
+ * @license
719
+ * Copyright 2025 Google LLC
720
+ *
721
+ * Licensed under the Apache License, Version 2.0 (the "License");
722
+ * you may not use this file except in compliance with the License.
723
+ * You may obtain a copy of the License at
724
+ *
725
+ * http://www.apache.org/licenses/LICENSE-2.0
726
+ *
727
+ * Unless required by applicable law or agreed to in writing, software
728
+ * distributed under the License is distributed on an "AS IS" BASIS,
729
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
730
+ * See the License for the specific language governing permissions and
731
+ * limitations under the License.
732
+ */
733
+ /**
734
+ * Base class for Firebase AI model APIs.
735
+ *
736
+ * Instances of this class are associated with a specific Firebase AI {@link Backend}
737
+ * and provide methods for interacting with the configured generative model.
738
+ *
739
+ * @public
740
+ */
741
+ class AIModel {
742
+ /**
743
+ * Constructs a new instance of the {@link AIModel} class.
744
+ *
745
+ * This constructor should only be called from subclasses that provide
746
+ * a model API.
747
+ *
748
+ * @param ai - an {@link AI} instance.
749
+ * @param modelName - The name of the model being used. It can be in one of the following formats:
750
+ * - `my-model` (short name, will resolve to `publishers/google/models/my-model`)
751
+ * - `models/my-model` (will resolve to `publishers/google/models/my-model`)
752
+ * - `publishers/my-publisher/models/my-model` (fully qualified model name)
753
+ *
754
+ * @throws If the `apiKey` or `projectId` fields are missing in your
755
+ * Firebase config.
756
+ *
757
+ * @internal
758
+ */
759
+ constructor(ai, modelName) {
760
+ var _a, _b, _c, _d, _e, _f;
761
+ if (!((_b = (_a = ai.app) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.apiKey)) {
762
+ throw new AIError("no-api-key" /* 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.`);
763
+ }
764
+ else if (!((_d = (_c = ai.app) === null || _c === void 0 ? void 0 : _c.options) === null || _d === void 0 ? void 0 : _d.projectId)) {
765
+ throw new AIError("no-project-id" /* 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.`);
766
+ }
767
+ else if (!((_f = (_e = ai.app) === null || _e === void 0 ? void 0 : _e.options) === null || _f === void 0 ? void 0 : _f.appId)) {
768
+ throw new AIError("no-app-id" /* 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.`);
769
+ }
770
+ else {
771
+ this._apiSettings = {
772
+ apiKey: ai.app.options.apiKey,
773
+ project: ai.app.options.projectId,
774
+ appId: ai.app.options.appId,
775
+ automaticDataCollectionEnabled: ai.app.automaticDataCollectionEnabled,
776
+ location: ai.location,
777
+ backend: ai.backend
778
+ };
779
+ if (_isFirebaseServerApp(ai.app) && ai.app.settings.appCheckToken) {
780
+ const token = ai.app.settings.appCheckToken;
781
+ this._apiSettings.getAppCheckToken = () => {
782
+ return Promise.resolve({ token });
783
+ };
784
+ }
785
+ else if (ai.appCheck) {
786
+ this._apiSettings.getAppCheckToken = () => ai.appCheck.getToken();
787
+ }
788
+ if (ai.auth) {
789
+ this._apiSettings.getAuthToken = () => ai.auth.getToken();
790
+ }
791
+ this.model = AIModel.normalizeModelName(modelName, this._apiSettings.backend.backendType);
792
+ }
793
+ }
794
+ /**
795
+ * Normalizes the given model name to a fully qualified model resource name.
796
+ *
797
+ * @param modelName - The model name to normalize.
798
+ * @returns The fully qualified model resource name.
799
+ *
800
+ * @internal
801
+ */
802
+ static normalizeModelName(modelName, backendType) {
803
+ if (backendType === BackendType.GOOGLE_AI) {
804
+ return AIModel.normalizeGoogleAIModelName(modelName);
805
+ }
806
+ else {
807
+ return AIModel.normalizeVertexAIModelName(modelName);
808
+ }
809
+ }
810
+ /**
811
+ * @internal
812
+ */
813
+ static normalizeGoogleAIModelName(modelName) {
814
+ return `models/${modelName}`;
815
+ }
816
+ /**
817
+ * @internal
818
+ */
819
+ static normalizeVertexAIModelName(modelName) {
820
+ let model;
821
+ if (modelName.includes('/')) {
822
+ if (modelName.startsWith('models/')) {
823
+ // Add 'publishers/google' if the user is only passing in 'models/model-name'.
824
+ model = `publishers/google/${modelName}`;
825
+ }
826
+ else {
827
+ // Any other custom format (e.g. tuned models) must be passed in correctly.
828
+ model = modelName;
829
+ }
830
+ }
831
+ else {
832
+ // If path is not included, assume it's a non-tuned model.
833
+ model = `publishers/google/models/${modelName}`;
834
+ }
835
+ return model;
836
+ }
837
+ }
838
+
839
+ /**
840
+ * @license
841
+ * Copyright 2024 Google LLC
842
+ *
843
+ * Licensed under the Apache License, Version 2.0 (the "License");
844
+ * you may not use this file except in compliance with the License.
845
+ * You may obtain a copy of the License at
846
+ *
847
+ * http://www.apache.org/licenses/LICENSE-2.0
848
+ *
849
+ * Unless required by applicable law or agreed to in writing, software
850
+ * distributed under the License is distributed on an "AS IS" BASIS,
851
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
852
+ * See the License for the specific language governing permissions and
853
+ * limitations under the License.
854
+ */
855
+ const logger = new Logger('@firebase/vertexai');
856
+
857
+ /**
858
+ * @license
859
+ * Copyright 2024 Google LLC
860
+ *
861
+ * Licensed under the Apache License, Version 2.0 (the "License");
862
+ * you may not use this file except in compliance with the License.
863
+ * You may obtain a copy of the License at
864
+ *
865
+ * http://www.apache.org/licenses/LICENSE-2.0
866
+ *
867
+ * Unless required by applicable law or agreed to in writing, software
868
+ * distributed under the License is distributed on an "AS IS" BASIS,
869
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
870
+ * See the License for the specific language governing permissions and
871
+ * limitations under the License.
872
+ */
873
+ var Task;
874
+ (function (Task) {
875
+ Task["GENERATE_CONTENT"] = "generateContent";
876
+ Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
877
+ Task["COUNT_TOKENS"] = "countTokens";
878
+ Task["PREDICT"] = "predict";
879
+ })(Task || (Task = {}));
880
+ class RequestUrl {
881
+ constructor(model, task, apiSettings, stream, requestOptions) {
882
+ this.model = model;
883
+ this.task = task;
884
+ this.apiSettings = apiSettings;
885
+ this.stream = stream;
886
+ this.requestOptions = requestOptions;
887
+ }
888
+ toString() {
889
+ const url = new URL(this.baseUrl); // Throws if the URL is invalid
890
+ url.pathname = `/${this.apiVersion}/${this.modelPath}:${this.task}`;
891
+ url.search = this.queryParams.toString();
892
+ return url.toString();
893
+ }
894
+ get baseUrl() {
895
+ var _a;
896
+ return ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.baseUrl) || DEFAULT_BASE_URL;
897
+ }
898
+ get apiVersion() {
899
+ return DEFAULT_API_VERSION; // TODO: allow user-set options if that feature becomes available
900
+ }
901
+ get modelPath() {
902
+ if (this.apiSettings.backend instanceof GoogleAIBackend) {
903
+ return `projects/${this.apiSettings.project}/${this.model}`;
904
+ }
905
+ else if (this.apiSettings.backend instanceof VertexAIBackend) {
906
+ return `projects/${this.apiSettings.project}/locations/${this.apiSettings.backend.location}/${this.model}`;
907
+ }
908
+ else {
909
+ throw new AIError("error" /* AIErrorCode.ERROR */, `Invalid backend: ${JSON.stringify(this.apiSettings.backend)}`);
910
+ }
911
+ }
912
+ get queryParams() {
913
+ const params = new URLSearchParams();
914
+ if (this.stream) {
915
+ params.set('alt', 'sse');
916
+ }
917
+ return params;
918
+ }
919
+ }
920
+ /**
921
+ * Log language and "fire/version" to x-goog-api-client
922
+ */
923
+ function getClientHeaders() {
924
+ const loggingTags = [];
925
+ loggingTags.push(`${LANGUAGE_TAG}/${PACKAGE_VERSION}`);
926
+ loggingTags.push(`fire/${PACKAGE_VERSION}`);
927
+ return loggingTags.join(' ');
928
+ }
929
+ async function getHeaders(url) {
930
+ const headers = new Headers();
931
+ headers.append('Content-Type', 'application/json');
932
+ headers.append('x-goog-api-client', getClientHeaders());
933
+ headers.append('x-goog-api-key', url.apiSettings.apiKey);
934
+ if (url.apiSettings.automaticDataCollectionEnabled) {
935
+ headers.append('X-Firebase-Appid', url.apiSettings.appId);
936
+ }
937
+ if (url.apiSettings.getAppCheckToken) {
938
+ const appCheckToken = await url.apiSettings.getAppCheckToken();
939
+ if (appCheckToken) {
940
+ headers.append('X-Firebase-AppCheck', appCheckToken.token);
941
+ if (appCheckToken.error) {
942
+ logger.warn(`Unable to obtain a valid App Check token: ${appCheckToken.error.message}`);
943
+ }
944
+ }
945
+ }
946
+ if (url.apiSettings.getAuthToken) {
947
+ const authToken = await url.apiSettings.getAuthToken();
948
+ if (authToken) {
949
+ headers.append('Authorization', `Firebase ${authToken.accessToken}`);
950
+ }
951
+ }
952
+ return headers;
953
+ }
954
+ async function constructRequest(model, task, apiSettings, stream, body, requestOptions) {
955
+ const url = new RequestUrl(model, task, apiSettings, stream, requestOptions);
956
+ return {
957
+ url: url.toString(),
958
+ fetchOptions: {
959
+ method: 'POST',
960
+ headers: await getHeaders(url),
961
+ body
962
+ }
963
+ };
964
+ }
965
+ async function makeRequest(model, task, apiSettings, stream, body, requestOptions) {
966
+ const url = new RequestUrl(model, task, apiSettings, stream, requestOptions);
967
+ let response;
968
+ let fetchTimeoutId;
969
+ try {
970
+ const request = await constructRequest(model, task, apiSettings, stream, body, requestOptions);
971
+ // Timeout is 180s by default
972
+ const timeoutMillis = (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) != null && requestOptions.timeout >= 0
973
+ ? requestOptions.timeout
974
+ : DEFAULT_FETCH_TIMEOUT_MS;
975
+ const abortController = new AbortController();
976
+ fetchTimeoutId = setTimeout(() => abortController.abort(), timeoutMillis);
977
+ request.fetchOptions.signal = abortController.signal;
978
+ response = await fetch(request.url, request.fetchOptions);
979
+ if (!response.ok) {
980
+ let message = '';
981
+ let errorDetails;
982
+ try {
983
+ const json = await response.json();
984
+ message = json.error.message;
985
+ if (json.error.details) {
986
+ message += ` ${JSON.stringify(json.error.details)}`;
987
+ errorDetails = json.error.details;
988
+ }
989
+ }
990
+ catch (e) {
991
+ // ignored
992
+ }
993
+ if (response.status === 403 &&
994
+ errorDetails.some((detail) => detail.reason === 'SERVICE_DISABLED') &&
995
+ errorDetails.some((detail) => {
996
+ var _a, _b;
997
+ return (_b = (_a = detail.links) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.description.includes('Google developers console API activation');
998
+ })) {
999
+ throw new AIError("api-not-enabled" /* AIErrorCode.API_NOT_ENABLED */, `The Firebase AI SDK requires the Firebase AI ` +
1000
+ `API ('firebasevertexai.googleapis.com') to be enabled in your ` +
1001
+ `Firebase project. Enable this API by visiting the Firebase Console ` +
1002
+ `at https://console.firebase.google.com/project/${url.apiSettings.project}/genai/ ` +
1003
+ `and clicking "Get started". If you enabled this API recently, ` +
1004
+ `wait a few minutes for the action to propagate to our systems and ` +
1005
+ `then retry.`, {
1006
+ status: response.status,
1007
+ statusText: response.statusText,
1008
+ errorDetails
1009
+ });
1010
+ }
1011
+ throw new AIError("fetch-error" /* AIErrorCode.FETCH_ERROR */, `Error fetching from ${url}: [${response.status} ${response.statusText}] ${message}`, {
1012
+ status: response.status,
1013
+ statusText: response.statusText,
1014
+ errorDetails
1015
+ });
1016
+ }
1017
+ }
1018
+ catch (e) {
1019
+ let err = e;
1020
+ if (e.code !== "fetch-error" /* AIErrorCode.FETCH_ERROR */ &&
1021
+ e.code !== "api-not-enabled" /* AIErrorCode.API_NOT_ENABLED */ &&
1022
+ e instanceof Error) {
1023
+ err = new AIError("error" /* AIErrorCode.ERROR */, `Error fetching from ${url.toString()}: ${e.message}`);
1024
+ err.stack = e.stack;
1025
+ }
1026
+ throw err;
1027
+ }
1028
+ finally {
1029
+ if (fetchTimeoutId) {
1030
+ clearTimeout(fetchTimeoutId);
1031
+ }
1032
+ }
1033
+ return response;
1034
+ }
1035
+
1036
+ /**
1037
+ * @license
1038
+ * Copyright 2024 Google LLC
1039
+ *
1040
+ * Licensed under the Apache License, Version 2.0 (the "License");
1041
+ * you may not use this file except in compliance with the License.
1042
+ * You may obtain a copy of the License at
1043
+ *
1044
+ * http://www.apache.org/licenses/LICENSE-2.0
1045
+ *
1046
+ * Unless required by applicable law or agreed to in writing, software
1047
+ * distributed under the License is distributed on an "AS IS" BASIS,
1048
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1049
+ * See the License for the specific language governing permissions and
1050
+ * limitations under the License.
1051
+ */
1052
+ /**
1053
+ * Creates an EnhancedGenerateContentResponse object that has helper functions and
1054
+ * other modifications that improve usability.
1055
+ */
1056
+ function createEnhancedContentResponse(response) {
1057
+ /**
1058
+ * The Vertex AI backend omits default values.
1059
+ * This causes the `index` property to be omitted from the first candidate in the
1060
+ * response, since it has index 0, and 0 is a default value.
1061
+ * See: https://github.com/firebase/firebase-js-sdk/issues/8566
1062
+ */
1063
+ if (response.candidates && !response.candidates[0].hasOwnProperty('index')) {
1064
+ response.candidates[0].index = 0;
1065
+ }
1066
+ const responseWithHelpers = addHelpers(response);
1067
+ return responseWithHelpers;
1068
+ }
1069
+ /**
1070
+ * Adds convenience helper methods to a response object, including stream
1071
+ * chunks (as long as each chunk is a complete GenerateContentResponse JSON).
1072
+ */
1073
+ function addHelpers(response) {
1074
+ response.text = () => {
1075
+ if (response.candidates && response.candidates.length > 0) {
1076
+ if (response.candidates.length > 1) {
1077
+ logger.warn(`This response had ${response.candidates.length} ` +
1078
+ `candidates. Returning text from the first candidate only. ` +
1079
+ `Access response.candidates directly to use the other candidates.`);
1080
+ }
1081
+ if (hadBadFinishReason(response.candidates[0])) {
1082
+ throw new AIError("response-error" /* AIErrorCode.RESPONSE_ERROR */, `Response error: ${formatBlockErrorMessage(response)}. Response body stored in error.response`, {
1083
+ response
1084
+ });
1085
+ }
1086
+ return getText(response);
1087
+ }
1088
+ else if (response.promptFeedback) {
1089
+ throw new AIError("response-error" /* AIErrorCode.RESPONSE_ERROR */, `Text not available. ${formatBlockErrorMessage(response)}`, {
1090
+ response
1091
+ });
1092
+ }
1093
+ return '';
1094
+ };
1095
+ response.inlineDataParts = () => {
1096
+ if (response.candidates && response.candidates.length > 0) {
1097
+ if (response.candidates.length > 1) {
1098
+ logger.warn(`This response had ${response.candidates.length} ` +
1099
+ `candidates. Returning data from the first candidate only. ` +
1100
+ `Access response.candidates directly to use the other candidates.`);
1101
+ }
1102
+ if (hadBadFinishReason(response.candidates[0])) {
1103
+ throw new AIError("response-error" /* AIErrorCode.RESPONSE_ERROR */, `Response error: ${formatBlockErrorMessage(response)}. Response body stored in error.response`, {
1104
+ response
1105
+ });
1106
+ }
1107
+ return getInlineDataParts(response);
1108
+ }
1109
+ else if (response.promptFeedback) {
1110
+ throw new AIError("response-error" /* AIErrorCode.RESPONSE_ERROR */, `Data not available. ${formatBlockErrorMessage(response)}`, {
1111
+ response
1112
+ });
1113
+ }
1114
+ return undefined;
1115
+ };
1116
+ response.functionCalls = () => {
1117
+ if (response.candidates && response.candidates.length > 0) {
1118
+ if (response.candidates.length > 1) {
1119
+ logger.warn(`This response had ${response.candidates.length} ` +
1120
+ `candidates. Returning function calls from the first candidate only. ` +
1121
+ `Access response.candidates directly to use the other candidates.`);
1122
+ }
1123
+ if (hadBadFinishReason(response.candidates[0])) {
1124
+ throw new AIError("response-error" /* AIErrorCode.RESPONSE_ERROR */, `Response error: ${formatBlockErrorMessage(response)}. Response body stored in error.response`, {
1125
+ response
1126
+ });
1127
+ }
1128
+ return getFunctionCalls(response);
1129
+ }
1130
+ else if (response.promptFeedback) {
1131
+ throw new AIError("response-error" /* AIErrorCode.RESPONSE_ERROR */, `Function call not available. ${formatBlockErrorMessage(response)}`, {
1132
+ response
1133
+ });
1134
+ }
1135
+ return undefined;
1136
+ };
1137
+ return response;
1138
+ }
1139
+ /**
1140
+ * Returns all text found in all parts of first candidate.
1141
+ */
1142
+ function getText(response) {
1143
+ var _a, _b, _c, _d;
1144
+ const textStrings = [];
1145
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
1146
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
1147
+ if (part.text) {
1148
+ textStrings.push(part.text);
1149
+ }
1150
+ }
1151
+ }
1152
+ if (textStrings.length > 0) {
1153
+ return textStrings.join('');
1154
+ }
1155
+ else {
1156
+ return '';
1157
+ }
1158
+ }
1159
+ /**
1160
+ * Returns {@link FunctionCall}s associated with first candidate.
1161
+ */
1162
+ function getFunctionCalls(response) {
1163
+ var _a, _b, _c, _d;
1164
+ const functionCalls = [];
1165
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
1166
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
1167
+ if (part.functionCall) {
1168
+ functionCalls.push(part.functionCall);
1169
+ }
1170
+ }
1171
+ }
1172
+ if (functionCalls.length > 0) {
1173
+ return functionCalls;
1174
+ }
1175
+ else {
1176
+ return undefined;
1177
+ }
1178
+ }
1179
+ /**
1180
+ * Returns {@link InlineDataPart}s in the first candidate if present.
1181
+ *
1182
+ * @internal
1183
+ */
1184
+ function getInlineDataParts(response) {
1185
+ var _a, _b, _c, _d;
1186
+ const data = [];
1187
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
1188
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
1189
+ if (part.inlineData) {
1190
+ data.push(part);
1191
+ }
1192
+ }
1193
+ }
1194
+ if (data.length > 0) {
1195
+ return data;
1196
+ }
1197
+ else {
1198
+ return undefined;
1199
+ }
1200
+ }
1201
+ const badFinishReasons = [FinishReason.RECITATION, FinishReason.SAFETY];
1202
+ function hadBadFinishReason(candidate) {
1203
+ return (!!candidate.finishReason &&
1204
+ badFinishReasons.includes(candidate.finishReason));
1205
+ }
1206
+ function formatBlockErrorMessage(response) {
1207
+ var _a, _b, _c;
1208
+ let message = '';
1209
+ if ((!response.candidates || response.candidates.length === 0) &&
1210
+ response.promptFeedback) {
1211
+ message += 'Response was blocked';
1212
+ if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) {
1213
+ message += ` due to ${response.promptFeedback.blockReason}`;
1214
+ }
1215
+ if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) {
1216
+ message += `: ${response.promptFeedback.blockReasonMessage}`;
1217
+ }
1218
+ }
1219
+ else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) {
1220
+ const firstCandidate = response.candidates[0];
1221
+ if (hadBadFinishReason(firstCandidate)) {
1222
+ message += `Candidate was blocked due to ${firstCandidate.finishReason}`;
1223
+ if (firstCandidate.finishMessage) {
1224
+ message += `: ${firstCandidate.finishMessage}`;
1225
+ }
1226
+ }
1227
+ }
1228
+ return message;
1229
+ }
1230
+ /**
1231
+ * Convert a generic successful fetch response body to an Imagen response object
1232
+ * that can be returned to the user. This converts the REST APIs response format to our
1233
+ * APIs representation of a response.
1234
+ *
1235
+ * @internal
1236
+ */
1237
+ async function handlePredictResponse(response) {
1238
+ var _a;
1239
+ const responseJson = await response.json();
1240
+ const images = [];
1241
+ let filteredReason = undefined;
1242
+ // The backend should always send a non-empty array of predictions if the response was successful.
1243
+ if (!responseJson.predictions || ((_a = responseJson.predictions) === null || _a === void 0 ? void 0 : _a.length) === 0) {
1244
+ throw new AIError("response-error" /* AIErrorCode.RESPONSE_ERROR */, 'No predictions or filtered reason received from Vertex AI. Please report this issue with the full error details at https://github.com/firebase/firebase-js-sdk/issues.');
1245
+ }
1246
+ for (const prediction of responseJson.predictions) {
1247
+ if (prediction.raiFilteredReason) {
1248
+ filteredReason = prediction.raiFilteredReason;
1249
+ }
1250
+ else if (prediction.mimeType && prediction.bytesBase64Encoded) {
1251
+ images.push({
1252
+ mimeType: prediction.mimeType,
1253
+ bytesBase64Encoded: prediction.bytesBase64Encoded
1254
+ });
1255
+ }
1256
+ else if (prediction.mimeType && prediction.gcsUri) {
1257
+ images.push({
1258
+ mimeType: prediction.mimeType,
1259
+ gcsURI: prediction.gcsUri
1260
+ });
1261
+ }
1262
+ else {
1263
+ throw new AIError("response-error" /* AIErrorCode.RESPONSE_ERROR */, `Predictions array in response has missing properties. Response: ${JSON.stringify(responseJson)}`);
1264
+ }
1265
+ }
1266
+ return { images, filteredReason };
1267
+ }
1268
+
1269
+ /**
1270
+ * @license
1271
+ * Copyright 2025 Google LLC
1272
+ *
1273
+ * Licensed under the Apache License, Version 2.0 (the "License");
1274
+ * you may not use this file except in compliance with the License.
1275
+ * You may obtain a copy of the License at
1276
+ *
1277
+ * http://www.apache.org/licenses/LICENSE-2.0
1278
+ *
1279
+ * Unless required by applicable law or agreed to in writing, software
1280
+ * distributed under the License is distributed on an "AS IS" BASIS,
1281
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1282
+ * See the License for the specific language governing permissions and
1283
+ * limitations under the License.
1284
+ */
1285
+ /**
1286
+ * This SDK supports both the Vertex AI Gemini API and the Gemini Developer API (using Google AI).
1287
+ * The public API prioritizes the format used by the Vertex AI Gemini API.
1288
+ * We avoid having two sets of types by translating requests and responses between the two API formats.
1289
+ * This translation allows developers to switch between the Vertex AI Gemini API and the Gemini Developer API
1290
+ * with minimal code changes.
1291
+ *
1292
+ * In here are functions that map requests and responses between the two API formats.
1293
+ * Requests in the Vertex AI format are mapped to the Google AI format before being sent.
1294
+ * Responses from the Google AI backend are mapped back to the Vertex AI format before being returned to the user.
1295
+ */
1296
+ /**
1297
+ * Maps a Vertex AI {@link GenerateContentRequest} to a format that can be sent to Google AI.
1298
+ *
1299
+ * @param generateContentRequest The {@link GenerateContentRequest} to map.
1300
+ * @returns A {@link GenerateContentResponse} that conforms to the Google AI format.
1301
+ *
1302
+ * @throws If the request contains properties that are unsupported by Google AI.
1303
+ *
1304
+ * @internal
1305
+ */
1306
+ function mapGenerateContentRequest(generateContentRequest) {
1307
+ var _a, _b;
1308
+ (_a = generateContentRequest.safetySettings) === null || _a === void 0 ? void 0 : _a.forEach(safetySetting => {
1309
+ if (safetySetting.method) {
1310
+ throw new AIError("unsupported" /* AIErrorCode.UNSUPPORTED */, 'SafetySetting.method is not supported in the the Gemini Developer API. Please remove this property.');
1311
+ }
1312
+ });
1313
+ if ((_b = generateContentRequest.generationConfig) === null || _b === void 0 ? void 0 : _b.topK) {
1314
+ const roundedTopK = Math.round(generateContentRequest.generationConfig.topK);
1315
+ if (roundedTopK !== generateContentRequest.generationConfig.topK) {
1316
+ logger.warn('topK in GenerationConfig has been rounded to the nearest integer to match the format for requests to the Gemini Developer API.');
1317
+ generateContentRequest.generationConfig.topK = roundedTopK;
1318
+ }
1319
+ }
1320
+ return generateContentRequest;
1321
+ }
1322
+ /**
1323
+ * Maps a {@link GenerateContentResponse} from Google AI to the format of the
1324
+ * {@link GenerateContentResponse} that we get from VertexAI that is exposed in the public API.
1325
+ *
1326
+ * @param googleAIResponse The {@link GenerateContentResponse} from Google AI.
1327
+ * @returns A {@link GenerateContentResponse} that conforms to the public API's format.
1328
+ *
1329
+ * @internal
1330
+ */
1331
+ function mapGenerateContentResponse(googleAIResponse) {
1332
+ const generateContentResponse = {
1333
+ candidates: googleAIResponse.candidates
1334
+ ? mapGenerateContentCandidates(googleAIResponse.candidates)
1335
+ : undefined,
1336
+ prompt: googleAIResponse.promptFeedback
1337
+ ? mapPromptFeedback(googleAIResponse.promptFeedback)
1338
+ : undefined,
1339
+ usageMetadata: googleAIResponse.usageMetadata
1340
+ };
1341
+ return generateContentResponse;
1342
+ }
1343
+ /**
1344
+ * Maps a Vertex AI {@link CountTokensRequest} to a format that can be sent to Google AI.
1345
+ *
1346
+ * @param countTokensRequest The {@link CountTokensRequest} to map.
1347
+ * @param model The model to count tokens with.
1348
+ * @returns A {@link CountTokensRequest} that conforms to the Google AI format.
1349
+ *
1350
+ * @internal
1351
+ */
1352
+ function mapCountTokensRequest(countTokensRequest, model) {
1353
+ const mappedCountTokensRequest = {
1354
+ generateContentRequest: Object.assign({ model }, countTokensRequest)
1355
+ };
1356
+ return mappedCountTokensRequest;
1357
+ }
1358
+ /**
1359
+ * Maps a Google AI {@link GoogleAIGenerateContentCandidate} to a format that conforms
1360
+ * to the Vertex AI API format.
1361
+ *
1362
+ * @param candidates The {@link GoogleAIGenerateContentCandidate} to map.
1363
+ * @returns A {@link GenerateContentCandidate} that conforms to the Vertex AI format.
1364
+ *
1365
+ * @throws If any {@link Part} in the candidates has a `videoMetadata` property.
1366
+ *
1367
+ * @internal
1368
+ */
1369
+ function mapGenerateContentCandidates(candidates) {
1370
+ const mappedCandidates = [];
1371
+ let mappedSafetyRatings;
1372
+ if (mappedCandidates) {
1373
+ candidates.forEach(candidate => {
1374
+ var _a;
1375
+ // Map citationSources to citations.
1376
+ let citationMetadata;
1377
+ if (candidate.citationMetadata) {
1378
+ citationMetadata = {
1379
+ citations: candidate.citationMetadata.citationSources
1380
+ };
1381
+ }
1382
+ // Assign missing candidate SafetyRatings properties to their defaults if undefined.
1383
+ if (candidate.safetyRatings) {
1384
+ mappedSafetyRatings = candidate.safetyRatings.map(safetyRating => {
1385
+ var _a, _b, _c;
1386
+ return Object.assign(Object.assign({}, safetyRating), { severity: (_a = safetyRating.severity) !== null && _a !== void 0 ? _a : HarmSeverity.HARM_SEVERITY_UNSUPPORTED, probabilityScore: (_b = safetyRating.probabilityScore) !== null && _b !== void 0 ? _b : 0, severityScore: (_c = safetyRating.severityScore) !== null && _c !== void 0 ? _c : 0 });
1387
+ });
1388
+ }
1389
+ // videoMetadata is not supported.
1390
+ // Throw early since developers may send a long video as input and only expect to pay
1391
+ // for inference on a small portion of the video.
1392
+ if ((_a = candidate.content) === null || _a === void 0 ? void 0 : _a.parts.some(part => part === null || part === void 0 ? void 0 : part.videoMetadata)) {
1393
+ throw new AIError("unsupported" /* AIErrorCode.UNSUPPORTED */, 'Part.videoMetadata is not supported in the Gemini Developer API. Please remove this property.');
1394
+ }
1395
+ const mappedCandidate = {
1396
+ index: candidate.index,
1397
+ content: candidate.content,
1398
+ finishReason: candidate.finishReason,
1399
+ finishMessage: candidate.finishMessage,
1400
+ safetyRatings: mappedSafetyRatings,
1401
+ citationMetadata,
1402
+ groundingMetadata: candidate.groundingMetadata
1403
+ };
1404
+ mappedCandidates.push(mappedCandidate);
1405
+ });
1406
+ }
1407
+ return mappedCandidates;
1408
+ }
1409
+ function mapPromptFeedback(promptFeedback) {
1410
+ // Assign missing SafetyRating properties to their defaults if undefined.
1411
+ const mappedSafetyRatings = [];
1412
+ promptFeedback.safetyRatings.forEach(safetyRating => {
1413
+ var _a, _b, _c;
1414
+ mappedSafetyRatings.push({
1415
+ category: safetyRating.category,
1416
+ probability: safetyRating.probability,
1417
+ severity: (_a = safetyRating.severity) !== null && _a !== void 0 ? _a : HarmSeverity.HARM_SEVERITY_UNSUPPORTED,
1418
+ probabilityScore: (_b = safetyRating.probabilityScore) !== null && _b !== void 0 ? _b : 0,
1419
+ severityScore: (_c = safetyRating.severityScore) !== null && _c !== void 0 ? _c : 0,
1420
+ blocked: safetyRating.blocked
1421
+ });
1422
+ });
1423
+ const mappedPromptFeedback = {
1424
+ blockReason: promptFeedback.blockReason,
1425
+ safetyRatings: mappedSafetyRatings,
1426
+ blockReasonMessage: promptFeedback.blockReasonMessage
1427
+ };
1428
+ return mappedPromptFeedback;
1429
+ }
1430
+
1431
+ /**
1432
+ * @license
1433
+ * Copyright 2024 Google LLC
1434
+ *
1435
+ * Licensed under the Apache License, Version 2.0 (the "License");
1436
+ * you may not use this file except in compliance with the License.
1437
+ * You may obtain a copy of the License at
1438
+ *
1439
+ * http://www.apache.org/licenses/LICENSE-2.0
1440
+ *
1441
+ * Unless required by applicable law or agreed to in writing, software
1442
+ * distributed under the License is distributed on an "AS IS" BASIS,
1443
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1444
+ * See the License for the specific language governing permissions and
1445
+ * limitations under the License.
1446
+ */
1447
+ const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
1448
+ /**
1449
+ * Process a response.body stream from the backend and return an
1450
+ * iterator that provides one complete GenerateContentResponse at a time
1451
+ * and a promise that resolves with a single aggregated
1452
+ * GenerateContentResponse.
1453
+ *
1454
+ * @param response - Response from a fetch call
1455
+ */
1456
+ function processStream(response, apiSettings) {
1457
+ const inputStream = response.body.pipeThrough(new TextDecoderStream('utf8', { fatal: true }));
1458
+ const responseStream = getResponseStream(inputStream);
1459
+ const [stream1, stream2] = responseStream.tee();
1460
+ return {
1461
+ stream: generateResponseSequence(stream1, apiSettings),
1462
+ response: getResponsePromise(stream2, apiSettings)
1463
+ };
1464
+ }
1465
+ async function getResponsePromise(stream, apiSettings) {
1466
+ const allResponses = [];
1467
+ const reader = stream.getReader();
1468
+ while (true) {
1469
+ const { done, value } = await reader.read();
1470
+ if (done) {
1471
+ let generateContentResponse = aggregateResponses(allResponses);
1472
+ if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
1473
+ generateContentResponse = mapGenerateContentResponse(generateContentResponse);
1474
+ }
1475
+ return createEnhancedContentResponse(generateContentResponse);
1476
+ }
1477
+ allResponses.push(value);
1478
+ }
1479
+ }
1480
+ function generateResponseSequence(stream, apiSettings) {
1481
+ return __asyncGenerator(this, arguments, function* generateResponseSequence_1() {
1482
+ const reader = stream.getReader();
1483
+ while (true) {
1484
+ const { value, done } = yield __await(reader.read());
1485
+ if (done) {
1486
+ break;
1487
+ }
1488
+ let enhancedResponse;
1489
+ if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
1490
+ enhancedResponse = createEnhancedContentResponse(mapGenerateContentResponse(value));
1491
+ }
1492
+ else {
1493
+ enhancedResponse = createEnhancedContentResponse(value);
1494
+ }
1495
+ yield yield __await(enhancedResponse);
1496
+ }
1497
+ });
1498
+ }
1499
+ /**
1500
+ * Reads a raw stream from the fetch response and join incomplete
1501
+ * chunks, returning a new stream that provides a single complete
1502
+ * GenerateContentResponse in each iteration.
1503
+ */
1504
+ function getResponseStream(inputStream) {
1505
+ const reader = inputStream.getReader();
1506
+ const stream = new ReadableStream({
1507
+ start(controller) {
1508
+ let currentText = '';
1509
+ return pump();
1510
+ function pump() {
1511
+ return reader.read().then(({ value, done }) => {
1512
+ if (done) {
1513
+ if (currentText.trim()) {
1514
+ controller.error(new AIError("parse-failed" /* AIErrorCode.PARSE_FAILED */, 'Failed to parse stream'));
1515
+ return;
1516
+ }
1517
+ controller.close();
1518
+ return;
1519
+ }
1520
+ currentText += value;
1521
+ let match = currentText.match(responseLineRE);
1522
+ let parsedResponse;
1523
+ while (match) {
1524
+ try {
1525
+ parsedResponse = JSON.parse(match[1]);
1526
+ }
1527
+ catch (e) {
1528
+ controller.error(new AIError("parse-failed" /* AIErrorCode.PARSE_FAILED */, `Error parsing JSON response: "${match[1]}`));
1529
+ return;
1530
+ }
1531
+ controller.enqueue(parsedResponse);
1532
+ currentText = currentText.substring(match[0].length);
1533
+ match = currentText.match(responseLineRE);
1534
+ }
1535
+ return pump();
1536
+ });
1537
+ }
1538
+ }
1539
+ });
1540
+ return stream;
1541
+ }
1542
+ /**
1543
+ * Aggregates an array of `GenerateContentResponse`s into a single
1544
+ * GenerateContentResponse.
1545
+ */
1546
+ function aggregateResponses(responses) {
1547
+ const lastResponse = responses[responses.length - 1];
1548
+ const aggregatedResponse = {
1549
+ promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback
1550
+ };
1551
+ for (const response of responses) {
1552
+ if (response.candidates) {
1553
+ for (const candidate of response.candidates) {
1554
+ // Index will be undefined if it's the first index (0), so we should use 0 if it's undefined.
1555
+ // See: https://github.com/firebase/firebase-js-sdk/issues/8566
1556
+ const i = candidate.index || 0;
1557
+ if (!aggregatedResponse.candidates) {
1558
+ aggregatedResponse.candidates = [];
1559
+ }
1560
+ if (!aggregatedResponse.candidates[i]) {
1561
+ aggregatedResponse.candidates[i] = {
1562
+ index: candidate.index
1563
+ };
1564
+ }
1565
+ // Keep overwriting, the last one will be final
1566
+ aggregatedResponse.candidates[i].citationMetadata =
1567
+ candidate.citationMetadata;
1568
+ aggregatedResponse.candidates[i].finishReason = candidate.finishReason;
1569
+ aggregatedResponse.candidates[i].finishMessage =
1570
+ candidate.finishMessage;
1571
+ aggregatedResponse.candidates[i].safetyRatings =
1572
+ candidate.safetyRatings;
1573
+ /**
1574
+ * Candidates should always have content and parts, but this handles
1575
+ * possible malformed responses.
1576
+ */
1577
+ if (candidate.content && candidate.content.parts) {
1578
+ if (!aggregatedResponse.candidates[i].content) {
1579
+ aggregatedResponse.candidates[i].content = {
1580
+ role: candidate.content.role || 'user',
1581
+ parts: []
1582
+ };
1583
+ }
1584
+ const newPart = {};
1585
+ for (const part of candidate.content.parts) {
1586
+ if (part.text !== undefined) {
1587
+ // The backend can send empty text parts. If these are sent back
1588
+ // (e.g. in chat history), the backend will respond with an error.
1589
+ // To prevent this, ignore empty text parts.
1590
+ if (part.text === '') {
1591
+ continue;
1592
+ }
1593
+ newPart.text = part.text;
1594
+ }
1595
+ if (part.functionCall) {
1596
+ newPart.functionCall = part.functionCall;
1597
+ }
1598
+ if (Object.keys(newPart).length === 0) {
1599
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, 'Part should have at least one property, but there are none. This is likely caused ' +
1600
+ 'by a malformed response from the backend.');
1601
+ }
1602
+ aggregatedResponse.candidates[i].content.parts.push(newPart);
1603
+ }
1604
+ }
1605
+ }
1606
+ }
1607
+ }
1608
+ return aggregatedResponse;
1609
+ }
1610
+
1611
+ /**
1612
+ * @license
1613
+ * Copyright 2024 Google LLC
1614
+ *
1615
+ * Licensed under the Apache License, Version 2.0 (the "License");
1616
+ * you may not use this file except in compliance with the License.
1617
+ * You may obtain a copy of the License at
1618
+ *
1619
+ * http://www.apache.org/licenses/LICENSE-2.0
1620
+ *
1621
+ * Unless required by applicable law or agreed to in writing, software
1622
+ * distributed under the License is distributed on an "AS IS" BASIS,
1623
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1624
+ * See the License for the specific language governing permissions and
1625
+ * limitations under the License.
1626
+ */
1627
+ async function generateContentStream(apiSettings, model, params, requestOptions) {
1628
+ if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
1629
+ params = mapGenerateContentRequest(params);
1630
+ }
1631
+ const response = await makeRequest(model, Task.STREAM_GENERATE_CONTENT, apiSettings,
1632
+ /* stream */ true, JSON.stringify(params), requestOptions);
1633
+ return processStream(response, apiSettings); // TODO: Map streaming responses
1634
+ }
1635
+ async function generateContent(apiSettings, model, params, requestOptions) {
1636
+ if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
1637
+ params = mapGenerateContentRequest(params);
1638
+ }
1639
+ const response = await makeRequest(model, Task.GENERATE_CONTENT, apiSettings,
1640
+ /* stream */ false, JSON.stringify(params), requestOptions);
1641
+ const generateContentResponse = await processGenerateContentResponse(response, apiSettings);
1642
+ const enhancedResponse = createEnhancedContentResponse(generateContentResponse);
1643
+ return {
1644
+ response: enhancedResponse
1645
+ };
1646
+ }
1647
+ async function processGenerateContentResponse(response, apiSettings) {
1648
+ const responseJson = await response.json();
1649
+ if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
1650
+ return mapGenerateContentResponse(responseJson);
1651
+ }
1652
+ else {
1653
+ return responseJson;
1654
+ }
1655
+ }
1656
+
1657
+ /**
1658
+ * @license
1659
+ * Copyright 2024 Google LLC
1660
+ *
1661
+ * Licensed under the Apache License, Version 2.0 (the "License");
1662
+ * you may not use this file except in compliance with the License.
1663
+ * You may obtain a copy of the License at
1664
+ *
1665
+ * http://www.apache.org/licenses/LICENSE-2.0
1666
+ *
1667
+ * Unless required by applicable law or agreed to in writing, software
1668
+ * distributed under the License is distributed on an "AS IS" BASIS,
1669
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1670
+ * See the License for the specific language governing permissions and
1671
+ * limitations under the License.
1672
+ */
1673
+ function formatSystemInstruction(input) {
1674
+ // null or undefined
1675
+ if (input == null) {
1676
+ return undefined;
1677
+ }
1678
+ else if (typeof input === 'string') {
1679
+ return { role: 'system', parts: [{ text: input }] };
1680
+ }
1681
+ else if (input.text) {
1682
+ return { role: 'system', parts: [input] };
1683
+ }
1684
+ else if (input.parts) {
1685
+ if (!input.role) {
1686
+ return { role: 'system', parts: input.parts };
1687
+ }
1688
+ else {
1689
+ return input;
1690
+ }
1691
+ }
1692
+ }
1693
+ function formatNewContent(request) {
1694
+ let newParts = [];
1695
+ if (typeof request === 'string') {
1696
+ newParts = [{ text: request }];
1697
+ }
1698
+ else {
1699
+ for (const partOrString of request) {
1700
+ if (typeof partOrString === 'string') {
1701
+ newParts.push({ text: partOrString });
1702
+ }
1703
+ else {
1704
+ newParts.push(partOrString);
1705
+ }
1706
+ }
1707
+ }
1708
+ return assignRoleToPartsAndValidateSendMessageRequest(newParts);
1709
+ }
1710
+ /**
1711
+ * When multiple Part types (i.e. FunctionResponsePart and TextPart) are
1712
+ * passed in a single Part array, we may need to assign different roles to each
1713
+ * part. Currently only FunctionResponsePart requires a role other than 'user'.
1714
+ * @private
1715
+ * @param parts Array of parts to pass to the model
1716
+ * @returns Array of content items
1717
+ */
1718
+ function assignRoleToPartsAndValidateSendMessageRequest(parts) {
1719
+ const userContent = { role: 'user', parts: [] };
1720
+ const functionContent = { role: 'function', parts: [] };
1721
+ let hasUserContent = false;
1722
+ let hasFunctionContent = false;
1723
+ for (const part of parts) {
1724
+ if ('functionResponse' in part) {
1725
+ functionContent.parts.push(part);
1726
+ hasFunctionContent = true;
1727
+ }
1728
+ else {
1729
+ userContent.parts.push(part);
1730
+ hasUserContent = true;
1731
+ }
1732
+ }
1733
+ if (hasUserContent && hasFunctionContent) {
1734
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, 'Within a single message, FunctionResponse cannot be mixed with other type of Part in the request for sending chat message.');
1735
+ }
1736
+ if (!hasUserContent && !hasFunctionContent) {
1737
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, 'No Content is provided for sending chat message.');
1738
+ }
1739
+ if (hasUserContent) {
1740
+ return userContent;
1741
+ }
1742
+ return functionContent;
1743
+ }
1744
+ function formatGenerateContentInput(params) {
1745
+ let formattedRequest;
1746
+ if (params.contents) {
1747
+ formattedRequest = params;
1748
+ }
1749
+ else {
1750
+ // Array or string
1751
+ const content = formatNewContent(params);
1752
+ formattedRequest = { contents: [content] };
1753
+ }
1754
+ if (params.systemInstruction) {
1755
+ formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);
1756
+ }
1757
+ return formattedRequest;
1758
+ }
1759
+ /**
1760
+ * Convert the user-defined parameters in {@link ImagenGenerationParams} to the format
1761
+ * that is expected from the REST API.
1762
+ *
1763
+ * @internal
1764
+ */
1765
+ function createPredictRequestBody(prompt, { gcsURI, imageFormat, addWatermark, numberOfImages = 1, negativePrompt, aspectRatio, safetyFilterLevel, personFilterLevel }) {
1766
+ // Properties that are undefined will be omitted from the JSON string that is sent in the request.
1767
+ const body = {
1768
+ instances: [
1769
+ {
1770
+ prompt
1771
+ }
1772
+ ],
1773
+ parameters: {
1774
+ storageUri: gcsURI,
1775
+ negativePrompt,
1776
+ sampleCount: numberOfImages,
1777
+ aspectRatio,
1778
+ outputOptions: imageFormat,
1779
+ addWatermark,
1780
+ safetyFilterLevel,
1781
+ personGeneration: personFilterLevel,
1782
+ includeRaiReason: true
1783
+ }
1784
+ };
1785
+ return body;
1786
+ }
1787
+
1788
+ /**
1789
+ * @license
1790
+ * Copyright 2024 Google LLC
1791
+ *
1792
+ * Licensed under the Apache License, Version 2.0 (the "License");
1793
+ * you may not use this file except in compliance with the License.
1794
+ * You may obtain a copy of the License at
1795
+ *
1796
+ * http://www.apache.org/licenses/LICENSE-2.0
1797
+ *
1798
+ * Unless required by applicable law or agreed to in writing, software
1799
+ * distributed under the License is distributed on an "AS IS" BASIS,
1800
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1801
+ * See the License for the specific language governing permissions and
1802
+ * limitations under the License.
1803
+ */
1804
+ // https://ai.google.dev/api/rest/v1beta/Content#part
1805
+ const VALID_PART_FIELDS = [
1806
+ 'text',
1807
+ 'inlineData',
1808
+ 'functionCall',
1809
+ 'functionResponse'
1810
+ ];
1811
+ const VALID_PARTS_PER_ROLE = {
1812
+ user: ['text', 'inlineData'],
1813
+ function: ['functionResponse'],
1814
+ model: ['text', 'functionCall'],
1815
+ // System instructions shouldn't be in history anyway.
1816
+ system: ['text']
1817
+ };
1818
+ const VALID_PREVIOUS_CONTENT_ROLES = {
1819
+ user: ['model'],
1820
+ function: ['model'],
1821
+ model: ['user', 'function'],
1822
+ // System instructions shouldn't be in history.
1823
+ system: []
1824
+ };
1825
+ function validateChatHistory(history) {
1826
+ let prevContent = null;
1827
+ for (const currContent of history) {
1828
+ const { role, parts } = currContent;
1829
+ if (!prevContent && role !== 'user') {
1830
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, `First Content should be with role 'user', got ${role}`);
1831
+ }
1832
+ if (!POSSIBLE_ROLES.includes(role)) {
1833
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, `Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);
1834
+ }
1835
+ if (!Array.isArray(parts)) {
1836
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, `Content should have 'parts' but property with an array of Parts`);
1837
+ }
1838
+ if (parts.length === 0) {
1839
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, `Each Content should have at least one part`);
1840
+ }
1841
+ const countFields = {
1842
+ text: 0,
1843
+ inlineData: 0,
1844
+ functionCall: 0,
1845
+ functionResponse: 0
1846
+ };
1847
+ for (const part of parts) {
1848
+ for (const key of VALID_PART_FIELDS) {
1849
+ if (key in part) {
1850
+ countFields[key] += 1;
1851
+ }
1852
+ }
1853
+ }
1854
+ const validParts = VALID_PARTS_PER_ROLE[role];
1855
+ for (const key of VALID_PART_FIELDS) {
1856
+ if (!validParts.includes(key) && countFields[key] > 0) {
1857
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, `Content with role '${role}' can't contain '${key}' part`);
1858
+ }
1859
+ }
1860
+ if (prevContent) {
1861
+ const validPreviousContentRoles = VALID_PREVIOUS_CONTENT_ROLES[role];
1862
+ if (!validPreviousContentRoles.includes(prevContent.role)) {
1863
+ throw new AIError("invalid-content" /* AIErrorCode.INVALID_CONTENT */, `Content with role '${role}' can't follow '${prevContent.role}'. Valid previous roles: ${JSON.stringify(VALID_PREVIOUS_CONTENT_ROLES)}`);
1864
+ }
1865
+ }
1866
+ prevContent = currContent;
1867
+ }
1868
+ }
1869
+
1870
+ /**
1871
+ * @license
1872
+ * Copyright 2024 Google LLC
1873
+ *
1874
+ * Licensed under the Apache License, Version 2.0 (the "License");
1875
+ * you may not use this file except in compliance with the License.
1876
+ * You may obtain a copy of the License at
1877
+ *
1878
+ * http://www.apache.org/licenses/LICENSE-2.0
1879
+ *
1880
+ * Unless required by applicable law or agreed to in writing, software
1881
+ * distributed under the License is distributed on an "AS IS" BASIS,
1882
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1883
+ * See the License for the specific language governing permissions and
1884
+ * limitations under the License.
1885
+ */
1886
+ /**
1887
+ * Do not log a message for this error.
1888
+ */
1889
+ const SILENT_ERROR = 'SILENT_ERROR';
1890
+ /**
1891
+ * ChatSession class that enables sending chat messages and stores
1892
+ * history of sent and received messages so far.
1893
+ *
1894
+ * @public
1895
+ */
1896
+ class ChatSession {
1897
+ constructor(apiSettings, model, params, requestOptions) {
1898
+ this.model = model;
1899
+ this.params = params;
1900
+ this.requestOptions = requestOptions;
1901
+ this._history = [];
1902
+ this._sendPromise = Promise.resolve();
1903
+ this._apiSettings = apiSettings;
1904
+ if (params === null || params === void 0 ? void 0 : params.history) {
1905
+ validateChatHistory(params.history);
1906
+ this._history = params.history;
1907
+ }
1908
+ }
1909
+ /**
1910
+ * Gets the chat history so far. Blocked prompts are not added to history.
1911
+ * Neither blocked candidates nor the prompts that generated them are added
1912
+ * to history.
1913
+ */
1914
+ async getHistory() {
1915
+ await this._sendPromise;
1916
+ return this._history;
1917
+ }
1918
+ /**
1919
+ * Sends a chat message and receives a non-streaming
1920
+ * {@link GenerateContentResult}
1921
+ */
1922
+ async sendMessage(request) {
1923
+ var _a, _b, _c, _d, _e;
1924
+ await this._sendPromise;
1925
+ const newContent = formatNewContent(request);
1926
+ const generateContentRequest = {
1927
+ safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
1928
+ generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
1929
+ tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
1930
+ toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
1931
+ systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1932
+ contents: [...this._history, newContent]
1933
+ };
1934
+ let finalResult = {};
1935
+ // Add onto the chain.
1936
+ this._sendPromise = this._sendPromise
1937
+ .then(() => generateContent(this._apiSettings, this.model, generateContentRequest, this.requestOptions))
1938
+ .then(result => {
1939
+ var _a, _b;
1940
+ if (result.response.candidates &&
1941
+ result.response.candidates.length > 0) {
1942
+ this._history.push(newContent);
1943
+ const responseContent = {
1944
+ parts: ((_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content.parts) || [],
1945
+ // Response seems to come back without a role set.
1946
+ role: ((_b = result.response.candidates) === null || _b === void 0 ? void 0 : _b[0].content.role) || 'model'
1947
+ };
1948
+ this._history.push(responseContent);
1949
+ }
1950
+ else {
1951
+ const blockErrorMessage = formatBlockErrorMessage(result.response);
1952
+ if (blockErrorMessage) {
1953
+ logger.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
1954
+ }
1955
+ }
1956
+ finalResult = result;
1957
+ });
1958
+ await this._sendPromise;
1959
+ return finalResult;
1960
+ }
1961
+ /**
1962
+ * Sends a chat message and receives the response as a
1963
+ * {@link GenerateContentStreamResult} containing an iterable stream
1964
+ * and a response promise.
1965
+ */
1966
+ async sendMessageStream(request) {
1967
+ var _a, _b, _c, _d, _e;
1968
+ await this._sendPromise;
1969
+ const newContent = formatNewContent(request);
1970
+ const generateContentRequest = {
1971
+ safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
1972
+ generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
1973
+ tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
1974
+ toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
1975
+ systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1976
+ contents: [...this._history, newContent]
1977
+ };
1978
+ const streamPromise = generateContentStream(this._apiSettings, this.model, generateContentRequest, this.requestOptions);
1979
+ // Add onto the chain.
1980
+ this._sendPromise = this._sendPromise
1981
+ .then(() => streamPromise)
1982
+ // This must be handled to avoid unhandled rejection, but jump
1983
+ // to the final catch block with a label to not log this error.
1984
+ .catch(_ignored => {
1985
+ throw new Error(SILENT_ERROR);
1986
+ })
1987
+ .then(streamResult => streamResult.response)
1988
+ .then(response => {
1989
+ if (response.candidates && response.candidates.length > 0) {
1990
+ this._history.push(newContent);
1991
+ const responseContent = Object.assign({}, response.candidates[0].content);
1992
+ // Response seems to come back without a role set.
1993
+ if (!responseContent.role) {
1994
+ responseContent.role = 'model';
1995
+ }
1996
+ this._history.push(responseContent);
1997
+ }
1998
+ else {
1999
+ const blockErrorMessage = formatBlockErrorMessage(response);
2000
+ if (blockErrorMessage) {
2001
+ logger.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
2002
+ }
2003
+ }
2004
+ })
2005
+ .catch(e => {
2006
+ // Errors in streamPromise are already catchable by the user as
2007
+ // streamPromise is returned.
2008
+ // Avoid duplicating the error message in logs.
2009
+ if (e.message !== SILENT_ERROR) {
2010
+ // Users do not have access to _sendPromise to catch errors
2011
+ // downstream from streamPromise, so they should not throw.
2012
+ logger.error(e);
2013
+ }
2014
+ });
2015
+ return streamPromise;
2016
+ }
2017
+ }
2018
+
2019
+ /**
2020
+ * @license
2021
+ * Copyright 2024 Google LLC
2022
+ *
2023
+ * Licensed under the Apache License, Version 2.0 (the "License");
2024
+ * you may not use this file except in compliance with the License.
2025
+ * You may obtain a copy of the License at
2026
+ *
2027
+ * http://www.apache.org/licenses/LICENSE-2.0
2028
+ *
2029
+ * Unless required by applicable law or agreed to in writing, software
2030
+ * distributed under the License is distributed on an "AS IS" BASIS,
2031
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2032
+ * See the License for the specific language governing permissions and
2033
+ * limitations under the License.
2034
+ */
2035
+ async function countTokens(apiSettings, model, params, requestOptions) {
2036
+ let body = '';
2037
+ if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
2038
+ const mappedParams = mapCountTokensRequest(params, model);
2039
+ body = JSON.stringify(mappedParams);
2040
+ }
2041
+ else {
2042
+ body = JSON.stringify(params);
2043
+ }
2044
+ const response = await makeRequest(model, Task.COUNT_TOKENS, apiSettings, false, body, requestOptions);
2045
+ return response.json();
2046
+ }
2047
+
2048
+ /**
2049
+ * @license
2050
+ * Copyright 2024 Google LLC
2051
+ *
2052
+ * Licensed under the Apache License, Version 2.0 (the "License");
2053
+ * you may not use this file except in compliance with the License.
2054
+ * You may obtain a copy of the License at
2055
+ *
2056
+ * http://www.apache.org/licenses/LICENSE-2.0
2057
+ *
2058
+ * Unless required by applicable law or agreed to in writing, software
2059
+ * distributed under the License is distributed on an "AS IS" BASIS,
2060
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2061
+ * See the License for the specific language governing permissions and
2062
+ * limitations under the License.
2063
+ */
2064
+ /**
2065
+ * Class for generative model APIs.
2066
+ * @public
2067
+ */
2068
+ class GenerativeModel extends AIModel {
2069
+ constructor(ai, modelParams, requestOptions) {
2070
+ super(ai, modelParams.model);
2071
+ this.generationConfig = modelParams.generationConfig || {};
2072
+ this.safetySettings = modelParams.safetySettings || [];
2073
+ this.tools = modelParams.tools;
2074
+ this.toolConfig = modelParams.toolConfig;
2075
+ this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);
2076
+ this.requestOptions = requestOptions || {};
2077
+ }
2078
+ /**
2079
+ * Makes a single non-streaming call to the model
2080
+ * and returns an object containing a single {@link GenerateContentResponse}.
2081
+ */
2082
+ async generateContent(request) {
2083
+ const formattedParams = formatGenerateContentInput(request);
2084
+ return generateContent(this._apiSettings, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction }, formattedParams), this.requestOptions);
2085
+ }
2086
+ /**
2087
+ * Makes a single streaming call to the model
2088
+ * and returns an object containing an iterable stream that iterates
2089
+ * over all chunks in the streaming response as well as
2090
+ * a promise that returns the final aggregated response.
2091
+ */
2092
+ async generateContentStream(request) {
2093
+ const formattedParams = formatGenerateContentInput(request);
2094
+ return generateContentStream(this._apiSettings, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction }, formattedParams), this.requestOptions);
2095
+ }
2096
+ /**
2097
+ * Gets a new {@link ChatSession} instance which can be used for
2098
+ * multi-turn chats.
2099
+ */
2100
+ startChat(startChatParams) {
2101
+ return new ChatSession(this._apiSettings, this.model, Object.assign({ tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, generationConfig: this.generationConfig, safetySettings: this.safetySettings }, startChatParams), this.requestOptions);
2102
+ }
2103
+ /**
2104
+ * Counts the tokens in the provided request.
2105
+ */
2106
+ async countTokens(request) {
2107
+ const formattedParams = formatGenerateContentInput(request);
2108
+ return countTokens(this._apiSettings, this.model, formattedParams);
2109
+ }
2110
+ }
2111
+
2112
+ /**
2113
+ * @license
2114
+ * Copyright 2025 Google LLC
2115
+ *
2116
+ * Licensed under the Apache License, Version 2.0 (the "License");
2117
+ * you may not use this file except in compliance with the License.
2118
+ * You may obtain a copy of the License at
2119
+ *
2120
+ * http://www.apache.org/licenses/LICENSE-2.0
2121
+ *
2122
+ * Unless required by applicable law or agreed to in writing, software
2123
+ * distributed under the License is distributed on an "AS IS" BASIS,
2124
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2125
+ * See the License for the specific language governing permissions and
2126
+ * limitations under the License.
2127
+ */
2128
+ /**
2129
+ * Class for Imagen model APIs.
2130
+ *
2131
+ * This class provides methods for generating images using the Imagen model.
2132
+ *
2133
+ * @example
2134
+ * ```javascript
2135
+ * const imagen = new ImagenModel(
2136
+ * ai,
2137
+ * {
2138
+ * model: 'imagen-3.0-generate-002'
2139
+ * }
2140
+ * );
2141
+ *
2142
+ * const response = await imagen.generateImages('A photo of a cat');
2143
+ * if (response.images.length > 0) {
2144
+ * console.log(response.images[0].bytesBase64Encoded);
2145
+ * }
2146
+ * ```
2147
+ *
2148
+ * @beta
2149
+ */
2150
+ class ImagenModel extends AIModel {
2151
+ /**
2152
+ * Constructs a new instance of the {@link ImagenModel} class.
2153
+ *
2154
+ * @param ai - an {@link AI} instance.
2155
+ * @param modelParams - Parameters to use when making requests to Imagen.
2156
+ * @param requestOptions - Additional options to use when making requests.
2157
+ *
2158
+ * @throws If the `apiKey` or `projectId` fields are missing in your
2159
+ * Firebase config.
2160
+ */
2161
+ constructor(ai, modelParams, requestOptions) {
2162
+ const { model, generationConfig, safetySettings } = modelParams;
2163
+ super(ai, model);
2164
+ this.requestOptions = requestOptions;
2165
+ this.generationConfig = generationConfig;
2166
+ this.safetySettings = safetySettings;
2167
+ }
2168
+ /**
2169
+ * Generates images using the Imagen model and returns them as
2170
+ * base64-encoded strings.
2171
+ *
2172
+ * @param prompt - A text prompt describing the image(s) to generate.
2173
+ * @returns A promise that resolves to an {@link ImagenGenerationResponse}
2174
+ * object containing the generated images.
2175
+ *
2176
+ * @throws If the request to generate images fails. This happens if the
2177
+ * prompt is blocked.
2178
+ *
2179
+ * @remarks
2180
+ * If the prompt was not blocked, but one or more of the generated images were filtered, the
2181
+ * returned object will have a `filteredReason` property.
2182
+ * If all images are filtered, the `images` array will be empty.
2183
+ *
2184
+ * @beta
2185
+ */
2186
+ async generateImages(prompt) {
2187
+ const body = createPredictRequestBody(prompt, Object.assign(Object.assign({}, this.generationConfig), this.safetySettings));
2188
+ const response = await makeRequest(this.model, Task.PREDICT, this._apiSettings,
2189
+ /* stream */ false, JSON.stringify(body), this.requestOptions);
2190
+ return handlePredictResponse(response);
2191
+ }
2192
+ /**
2193
+ * Generates images to Cloud Storage for Firebase using the Imagen model.
2194
+ *
2195
+ * @internal This method is temporarily internal.
2196
+ *
2197
+ * @param prompt - A text prompt describing the image(s) to generate.
2198
+ * @param gcsURI - The URI of file stored in a Cloud Storage for Firebase bucket.
2199
+ * This should be a directory. For example, `gs://my-bucket/my-directory/`.
2200
+ * @returns A promise that resolves to an {@link ImagenGenerationResponse}
2201
+ * object containing the URLs of the generated images.
2202
+ *
2203
+ * @throws If the request fails to generate images fails. This happens if
2204
+ * the prompt is blocked.
2205
+ *
2206
+ * @remarks
2207
+ * If the prompt was not blocked, but one or more of the generated images were filtered, the
2208
+ * returned object will have a `filteredReason` property.
2209
+ * If all images are filtered, the `images` array will be empty.
2210
+ */
2211
+ async generateImagesGCS(prompt, gcsURI) {
2212
+ const body = createPredictRequestBody(prompt, Object.assign(Object.assign({ gcsURI }, this.generationConfig), this.safetySettings));
2213
+ const response = await makeRequest(this.model, Task.PREDICT, this._apiSettings,
2214
+ /* stream */ false, JSON.stringify(body), this.requestOptions);
2215
+ return handlePredictResponse(response);
2216
+ }
2217
+ }
2218
+
2219
+ /**
2220
+ * @license
2221
+ * Copyright 2024 Google LLC
2222
+ *
2223
+ * Licensed under the Apache License, Version 2.0 (the "License");
2224
+ * you may not use this file except in compliance with the License.
2225
+ * You may obtain a copy of the License at
2226
+ *
2227
+ * http://www.apache.org/licenses/LICENSE-2.0
2228
+ *
2229
+ * Unless required by applicable law or agreed to in writing, software
2230
+ * distributed under the License is distributed on an "AS IS" BASIS,
2231
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2232
+ * See the License for the specific language governing permissions and
2233
+ * limitations under the License.
2234
+ */
2235
+ /**
2236
+ * Parent class encompassing all Schema types, with static methods that
2237
+ * allow building specific Schema types. This class can be converted with
2238
+ * `JSON.stringify()` into a JSON string accepted by Vertex AI REST endpoints.
2239
+ * (This string conversion is automatically done when calling SDK methods.)
2240
+ * @public
2241
+ */
2242
+ class Schema {
2243
+ constructor(schemaParams) {
2244
+ // eslint-disable-next-line guard-for-in
2245
+ for (const paramKey in schemaParams) {
2246
+ this[paramKey] = schemaParams[paramKey];
2247
+ }
2248
+ // Ensure these are explicitly set to avoid TS errors.
2249
+ this.type = schemaParams.type;
2250
+ this.nullable = schemaParams.hasOwnProperty('nullable')
2251
+ ? !!schemaParams.nullable
2252
+ : false;
2253
+ }
2254
+ /**
2255
+ * Defines how this Schema should be serialized as JSON.
2256
+ * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior
2257
+ * @internal
2258
+ */
2259
+ toJSON() {
2260
+ const obj = {
2261
+ type: this.type
2262
+ };
2263
+ for (const prop in this) {
2264
+ if (this.hasOwnProperty(prop) && this[prop] !== undefined) {
2265
+ if (prop !== 'required' || this.type === SchemaType.OBJECT) {
2266
+ obj[prop] = this[prop];
2267
+ }
2268
+ }
2269
+ }
2270
+ return obj;
2271
+ }
2272
+ static array(arrayParams) {
2273
+ return new ArraySchema(arrayParams, arrayParams.items);
2274
+ }
2275
+ static object(objectParams) {
2276
+ return new ObjectSchema(objectParams, objectParams.properties, objectParams.optionalProperties);
2277
+ }
2278
+ // eslint-disable-next-line id-blacklist
2279
+ static string(stringParams) {
2280
+ return new StringSchema(stringParams);
2281
+ }
2282
+ static enumString(stringParams) {
2283
+ return new StringSchema(stringParams, stringParams.enum);
2284
+ }
2285
+ static integer(integerParams) {
2286
+ return new IntegerSchema(integerParams);
2287
+ }
2288
+ // eslint-disable-next-line id-blacklist
2289
+ static number(numberParams) {
2290
+ return new NumberSchema(numberParams);
2291
+ }
2292
+ // eslint-disable-next-line id-blacklist
2293
+ static boolean(booleanParams) {
2294
+ return new BooleanSchema(booleanParams);
2295
+ }
2296
+ }
2297
+ /**
2298
+ * Schema class for "integer" types.
2299
+ * @public
2300
+ */
2301
+ class IntegerSchema extends Schema {
2302
+ constructor(schemaParams) {
2303
+ super(Object.assign({ type: SchemaType.INTEGER }, schemaParams));
2304
+ }
2305
+ }
2306
+ /**
2307
+ * Schema class for "number" types.
2308
+ * @public
2309
+ */
2310
+ class NumberSchema extends Schema {
2311
+ constructor(schemaParams) {
2312
+ super(Object.assign({ type: SchemaType.NUMBER }, schemaParams));
2313
+ }
2314
+ }
2315
+ /**
2316
+ * Schema class for "boolean" types.
2317
+ * @public
2318
+ */
2319
+ class BooleanSchema extends Schema {
2320
+ constructor(schemaParams) {
2321
+ super(Object.assign({ type: SchemaType.BOOLEAN }, schemaParams));
2322
+ }
2323
+ }
2324
+ /**
2325
+ * Schema class for "string" types. Can be used with or without
2326
+ * enum values.
2327
+ * @public
2328
+ */
2329
+ class StringSchema extends Schema {
2330
+ constructor(schemaParams, enumValues) {
2331
+ super(Object.assign({ type: SchemaType.STRING }, schemaParams));
2332
+ this.enum = enumValues;
2333
+ }
2334
+ /**
2335
+ * @internal
2336
+ */
2337
+ toJSON() {
2338
+ const obj = super.toJSON();
2339
+ if (this.enum) {
2340
+ obj['enum'] = this.enum;
2341
+ }
2342
+ return obj;
2343
+ }
2344
+ }
2345
+ /**
2346
+ * Schema class for "array" types.
2347
+ * The `items` param should refer to the type of item that can be a member
2348
+ * of the array.
2349
+ * @public
2350
+ */
2351
+ class ArraySchema extends Schema {
2352
+ constructor(schemaParams, items) {
2353
+ super(Object.assign({ type: SchemaType.ARRAY }, schemaParams));
2354
+ this.items = items;
2355
+ }
2356
+ /**
2357
+ * @internal
2358
+ */
2359
+ toJSON() {
2360
+ const obj = super.toJSON();
2361
+ obj.items = this.items.toJSON();
2362
+ return obj;
2363
+ }
2364
+ }
2365
+ /**
2366
+ * Schema class for "object" types.
2367
+ * The `properties` param must be a map of `Schema` objects.
2368
+ * @public
2369
+ */
2370
+ class ObjectSchema extends Schema {
2371
+ constructor(schemaParams, properties, optionalProperties = []) {
2372
+ super(Object.assign({ type: SchemaType.OBJECT }, schemaParams));
2373
+ this.properties = properties;
2374
+ this.optionalProperties = optionalProperties;
2375
+ }
2376
+ /**
2377
+ * @internal
2378
+ */
2379
+ toJSON() {
2380
+ const obj = super.toJSON();
2381
+ obj.properties = Object.assign({}, this.properties);
2382
+ const required = [];
2383
+ if (this.optionalProperties) {
2384
+ for (const propertyKey of this.optionalProperties) {
2385
+ if (!this.properties.hasOwnProperty(propertyKey)) {
2386
+ throw new AIError("invalid-schema" /* AIErrorCode.INVALID_SCHEMA */, `Property "${propertyKey}" specified in "optionalProperties" does not exist.`);
2387
+ }
2388
+ }
2389
+ }
2390
+ for (const propertyKey in this.properties) {
2391
+ if (this.properties.hasOwnProperty(propertyKey)) {
2392
+ obj.properties[propertyKey] = this.properties[propertyKey].toJSON();
2393
+ if (!this.optionalProperties.includes(propertyKey)) {
2394
+ required.push(propertyKey);
2395
+ }
2396
+ }
2397
+ }
2398
+ if (required.length > 0) {
2399
+ obj.required = required;
2400
+ }
2401
+ delete obj.optionalProperties;
2402
+ return obj;
2403
+ }
2404
+ }
2405
+
2406
+ /**
2407
+ * @license
2408
+ * Copyright 2025 Google LLC
2409
+ *
2410
+ * Licensed under the Apache License, Version 2.0 (the "License");
2411
+ * you may not use this file except in compliance with the License.
2412
+ * You may obtain a copy of the License at
2413
+ *
2414
+ * http://www.apache.org/licenses/LICENSE-2.0
2415
+ *
2416
+ * Unless required by applicable law or agreed to in writing, software
2417
+ * distributed under the License is distributed on an "AS IS" BASIS,
2418
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2419
+ * See the License for the specific language governing permissions and
2420
+ * limitations under the License.
2421
+ */
2422
+ /**
2423
+ * Defines the image format for images generated by Imagen.
2424
+ *
2425
+ * Use this class to specify the desired format (JPEG or PNG) and compression quality
2426
+ * for images generated by Imagen. This is typically included as part of
2427
+ * {@link ImagenModelParams}.
2428
+ *
2429
+ * @example
2430
+ * ```javascript
2431
+ * const imagenModelParams = {
2432
+ * // ... other ImagenModelParams
2433
+ * imageFormat: ImagenImageFormat.jpeg(75) // JPEG with a compression level of 75.
2434
+ * }
2435
+ * ```
2436
+ *
2437
+ * @beta
2438
+ */
2439
+ class ImagenImageFormat {
2440
+ constructor() {
2441
+ this.mimeType = 'image/png';
2442
+ }
2443
+ /**
2444
+ * Creates an {@link ImagenImageFormat} for a JPEG image.
2445
+ *
2446
+ * @param compressionQuality - The level of compression (a number between 0 and 100).
2447
+ * @returns An {@link ImagenImageFormat} object for a JPEG image.
2448
+ *
2449
+ * @beta
2450
+ */
2451
+ static jpeg(compressionQuality) {
2452
+ if (compressionQuality &&
2453
+ (compressionQuality < 0 || compressionQuality > 100)) {
2454
+ logger.warn(`Invalid JPEG compression quality of ${compressionQuality} specified; the supported range is [0, 100].`);
2455
+ }
2456
+ return { mimeType: 'image/jpeg', compressionQuality };
2457
+ }
2458
+ /**
2459
+ * Creates an {@link ImagenImageFormat} for a PNG image.
2460
+ *
2461
+ * @returns An {@link ImagenImageFormat} object for a PNG image.
2462
+ *
2463
+ * @beta
2464
+ */
2465
+ static png() {
2466
+ return { mimeType: 'image/png' };
2467
+ }
2468
+ }
2469
+
2470
+ /**
2471
+ * @license
2472
+ * Copyright 2024 Google LLC
2473
+ *
2474
+ * Licensed under the Apache License, Version 2.0 (the "License");
2475
+ * you may not use this file except in compliance with the License.
2476
+ * You may obtain a copy of the License at
2477
+ *
2478
+ * http://www.apache.org/licenses/LICENSE-2.0
2479
+ *
2480
+ * Unless required by applicable law or agreed to in writing, software
2481
+ * distributed under the License is distributed on an "AS IS" BASIS,
2482
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2483
+ * See the License for the specific language governing permissions and
2484
+ * limitations under the License.
2485
+ */
2486
+ /**
2487
+ * @deprecated Use the new {@link AIModel} instead. The Vertex AI in Firebase SDK has been
2488
+ * replaced with the Firebase AI SDK to accommodate the evolving set of supported features and
2489
+ * services. For migration details, see the {@link https://firebase.google.com/docs/vertex-ai/migrate-to-latest-sdk | migration guide}.
2490
+ *
2491
+ * Base class for Firebase AI model APIs.
2492
+ *
2493
+ * @public
2494
+ */
2495
+ const VertexAIModel = AIModel;
2496
+ /**
2497
+ * @deprecated Use the new {@link AIError} instead. The Vertex AI in Firebase SDK has been
2498
+ * replaced with the Firebase AI SDK to accommodate the evolving set of supported features and
2499
+ * services. For migration details, see the {@link https://firebase.google.com/docs/vertex-ai/migrate-to-latest-sdk | migration guide}.
2500
+ *
2501
+ * Error class for the Firebase AI SDK.
2502
+ *
2503
+ * @public
2504
+ */
2505
+ const VertexAIError = AIError;
2506
+ /**
2507
+ * @deprecated Use the new {@link getAI | getAI()} instead. The Vertex AI in Firebase SDK has been
2508
+ * replaced with the Firebase AI SDK to accommodate the evolving set of supported features and
2509
+ * services. For migration details, see the {@link https://firebase.google.com/docs/vertex-ai/migrate-to-latest-sdk | migration guide}.
2510
+ *
2511
+ * Returns a {@link VertexAI} instance for the given app, configured to use the
2512
+ * Vertex AI Gemini API. This instance will be
2513
+ * configured to use the Vertex AI Gemini API.
2514
+ *
2515
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
2516
+ * @param options - Options to configure the Vertex AI instance, including the location.
2517
+ *
2518
+ * @public
2519
+ */
2520
+ function getVertexAI(app = getApp(), options) {
2521
+ app = getModularInstance(app);
2522
+ // Dependencies
2523
+ const AIProvider = _getProvider(app, AI_TYPE);
2524
+ const backend = new VertexAIBackend(options === null || options === void 0 ? void 0 : options.location);
2525
+ const identifier = encodeInstanceIdentifier(backend);
2526
+ return AIProvider.getImmediate({
2527
+ identifier
2528
+ });
2529
+ }
2530
+ /**
2531
+ * Returns the default {@link AI} instance that is associated with the provided
2532
+ * {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new instance with the
2533
+ * default settings.
2534
+ *
2535
+ * @example
2536
+ * ```javascript
2537
+ * const ai = getAI(app);
2538
+ * ```
2539
+ *
2540
+ * @example
2541
+ * ```javascript
2542
+ * // Get an AI instance configured to use the Gemini Developer API (via Google AI).
2543
+ * const ai = getAI(app, { backend: new GoogleAIBackend() });
2544
+ * ```
2545
+ *
2546
+ * @example
2547
+ * ```javascript
2548
+ * // Get an AI instance configured to use the Vertex AI Gemini API.
2549
+ * const ai = getAI(app, { backend: new VertexAIBackend() });
2550
+ * ```
2551
+ *
2552
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
2553
+ * @param options - {@link AIOptions} that configure the AI instance.
2554
+ * @returns The default {@link AI} instance for the given {@link @firebase/app#FirebaseApp}.
2555
+ *
2556
+ * @public
2557
+ */
2558
+ function getAI(app = getApp(), options = { backend: new GoogleAIBackend() }) {
2559
+ app = getModularInstance(app);
2560
+ // Dependencies
2561
+ const AIProvider = _getProvider(app, AI_TYPE);
2562
+ const identifier = encodeInstanceIdentifier(options.backend);
2563
+ return AIProvider.getImmediate({
2564
+ identifier
2565
+ });
2566
+ }
2567
+ /**
2568
+ * Returns a {@link GenerativeModel} class with methods for inference
2569
+ * and other functionality.
2570
+ *
2571
+ * @public
2572
+ */
2573
+ function getGenerativeModel(ai, modelParams, requestOptions) {
2574
+ if (!modelParams.model) {
2575
+ throw new AIError("no-model" /* AIErrorCode.NO_MODEL */, `Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })`);
2576
+ }
2577
+ return new GenerativeModel(ai, modelParams, requestOptions);
2578
+ }
2579
+ /**
2580
+ * Returns an {@link ImagenModel} class with methods for using Imagen.
2581
+ *
2582
+ * Only Imagen 3 models (named `imagen-3.0-*`) are supported.
2583
+ *
2584
+ * @param ai - An {@link AI} instance.
2585
+ * @param modelParams - Parameters to use when making Imagen requests.
2586
+ * @param requestOptions - Additional options to use when making requests.
2587
+ *
2588
+ * @throws If the `apiKey` or `projectId` fields are missing in your
2589
+ * Firebase config.
2590
+ *
2591
+ * @beta
2592
+ */
2593
+ function getImagenModel(ai, modelParams, requestOptions) {
2594
+ if (!modelParams.model) {
2595
+ throw new AIError("no-model" /* AIErrorCode.NO_MODEL */, `Must provide a model name. Example: getImagenModel({ model: 'my-model-name' })`);
2596
+ }
2597
+ return new ImagenModel(ai, modelParams, requestOptions);
2598
+ }
2599
+
2600
+ /**
2601
+ * The Firebase AI Web SDK.
2602
+ *
2603
+ * @packageDocumentation
2604
+ */
2605
+ function registerAI() {
2606
+ _registerComponent(new Component(AI_TYPE, (container, { instanceIdentifier }) => {
2607
+ if (!instanceIdentifier) {
2608
+ throw new AIError("error" /* AIErrorCode.ERROR */, 'AIService instance identifier is undefined.');
2609
+ }
2610
+ const backend = decodeInstanceIdentifier(instanceIdentifier);
2611
+ // getImmediate for FirebaseApp will always succeed
2612
+ const app = container.getProvider('app').getImmediate();
2613
+ const auth = container.getProvider('auth-internal');
2614
+ const appCheckProvider = container.getProvider('app-check-internal');
2615
+ return new AIService(app, backend, auth, appCheckProvider);
2616
+ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
2617
+ registerVersion(name, version, 'node');
2618
+ // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
2619
+ registerVersion(name, version, 'esm2017');
2620
+ }
2621
+ registerAI();
2622
+
2623
+ export { AIError, AIModel, ArraySchema, Backend, BackendType, BlockReason, BooleanSchema, ChatSession, FinishReason, FunctionCallingMode, GenerativeModel, GoogleAIBackend, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, ImagenAspectRatio, ImagenImageFormat, ImagenModel, ImagenPersonFilterLevel, ImagenSafetyFilterLevel, IntegerSchema, Modality, NumberSchema, ObjectSchema, POSSIBLE_ROLES, ResponseModality, Schema, SchemaType, StringSchema, VertexAIBackend, VertexAIError, VertexAIModel, getAI, getGenerativeModel, getImagenModel, getVertexAI };
2624
+ //# sourceMappingURL=index.node.mjs.map