@firebase/ai 1.2.2-canary.f92069a21 → 1.2.2-eap-ai-hybridinference.58d92df33

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.
@@ -5,7 +5,7 @@ import { Logger } from '@firebase/logger';
5
5
  import { __asyncGenerator, __await } from 'tslib';
6
6
 
7
7
  var name = "@firebase/ai";
8
- var version = "1.2.2-canary.f92069a21";
8
+ var version = "1.2.2-eap-ai-hybridinference.58d92df33";
9
9
 
10
10
  /**
11
11
  * @license
@@ -1624,20 +1624,38 @@ function aggregateResponses(responses) {
1624
1624
  * See the License for the specific language governing permissions and
1625
1625
  * limitations under the License.
1626
1626
  */
1627
- async function generateContentStream(apiSettings, model, params, requestOptions) {
1627
+ async function generateContentStreamOnCloud(apiSettings, model, params, requestOptions) {
1628
1628
  if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
1629
1629
  params = mapGenerateContentRequest(params);
1630
1630
  }
1631
- const response = await makeRequest(model, Task.STREAM_GENERATE_CONTENT, apiSettings,
1631
+ return makeRequest(model, Task.STREAM_GENERATE_CONTENT, apiSettings,
1632
1632
  /* stream */ true, JSON.stringify(params), requestOptions);
1633
+ }
1634
+ async function generateContentStream(apiSettings, model, params, chromeAdapter, requestOptions) {
1635
+ let response;
1636
+ if (await chromeAdapter.isAvailable(params)) {
1637
+ response = await chromeAdapter.generateContentStream(params);
1638
+ }
1639
+ else {
1640
+ response = await generateContentStreamOnCloud(apiSettings, model, params, requestOptions);
1641
+ }
1633
1642
  return processStream(response, apiSettings); // TODO: Map streaming responses
1634
1643
  }
1635
- async function generateContent(apiSettings, model, params, requestOptions) {
1644
+ async function generateContentOnCloud(apiSettings, model, params, requestOptions) {
1636
1645
  if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
1637
1646
  params = mapGenerateContentRequest(params);
1638
1647
  }
1639
- const response = await makeRequest(model, Task.GENERATE_CONTENT, apiSettings,
1648
+ return makeRequest(model, Task.GENERATE_CONTENT, apiSettings,
1640
1649
  /* stream */ false, JSON.stringify(params), requestOptions);
1650
+ }
1651
+ async function generateContent(apiSettings, model, params, chromeAdapter, requestOptions) {
1652
+ let response;
1653
+ if (await chromeAdapter.isAvailable(params)) {
1654
+ response = await chromeAdapter.generateContent(params);
1655
+ }
1656
+ else {
1657
+ response = await generateContentOnCloud(apiSettings, model, params, requestOptions);
1658
+ }
1641
1659
  const generateContentResponse = await processGenerateContentResponse(response, apiSettings);
1642
1660
  const enhancedResponse = createEnhancedContentResponse(generateContentResponse);
1643
1661
  return {
@@ -1894,8 +1912,9 @@ const SILENT_ERROR = 'SILENT_ERROR';
1894
1912
  * @public
1895
1913
  */
1896
1914
  class ChatSession {
1897
- constructor(apiSettings, model, params, requestOptions) {
1915
+ constructor(apiSettings, model, chromeAdapter, params, requestOptions) {
1898
1916
  this.model = model;
1917
+ this.chromeAdapter = chromeAdapter;
1899
1918
  this.params = params;
1900
1919
  this.requestOptions = requestOptions;
1901
1920
  this._history = [];
@@ -1934,7 +1953,7 @@ class ChatSession {
1934
1953
  let finalResult = {};
1935
1954
  // Add onto the chain.
1936
1955
  this._sendPromise = this._sendPromise
1937
- .then(() => generateContent(this._apiSettings, this.model, generateContentRequest, this.requestOptions))
1956
+ .then(() => generateContent(this._apiSettings, this.model, generateContentRequest, this.chromeAdapter, this.requestOptions))
1938
1957
  .then(result => {
1939
1958
  var _a, _b;
1940
1959
  if (result.response.candidates &&
@@ -1975,7 +1994,7 @@ class ChatSession {
1975
1994
  systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1976
1995
  contents: [...this._history, newContent]
1977
1996
  };
1978
- const streamPromise = generateContentStream(this._apiSettings, this.model, generateContentRequest, this.requestOptions);
1997
+ const streamPromise = generateContentStream(this._apiSettings, this.model, generateContentRequest, this.chromeAdapter, this.requestOptions);
1979
1998
  // Add onto the chain.
1980
1999
  this._sendPromise = this._sendPromise
1981
2000
  .then(() => streamPromise)
@@ -2032,7 +2051,7 @@ class ChatSession {
2032
2051
  * See the License for the specific language governing permissions and
2033
2052
  * limitations under the License.
2034
2053
  */
2035
- async function countTokens(apiSettings, model, params, requestOptions) {
2054
+ async function countTokensOnCloud(apiSettings, model, params, requestOptions) {
2036
2055
  let body = '';
2037
2056
  if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
2038
2057
  const mappedParams = mapCountTokensRequest(params, model);
@@ -2044,6 +2063,12 @@ async function countTokens(apiSettings, model, params, requestOptions) {
2044
2063
  const response = await makeRequest(model, Task.COUNT_TOKENS, apiSettings, false, body, requestOptions);
2045
2064
  return response.json();
2046
2065
  }
2066
+ async function countTokens(apiSettings, model, params, chromeAdapter, requestOptions) {
2067
+ if (await chromeAdapter.isAvailable(params)) {
2068
+ return (await chromeAdapter.countTokens(params)).json();
2069
+ }
2070
+ return countTokensOnCloud(apiSettings, model, params, requestOptions);
2071
+ }
2047
2072
 
2048
2073
  /**
2049
2074
  * @license
@@ -2066,8 +2091,9 @@ async function countTokens(apiSettings, model, params, requestOptions) {
2066
2091
  * @public
2067
2092
  */
2068
2093
  class GenerativeModel extends AIModel {
2069
- constructor(ai, modelParams, requestOptions) {
2094
+ constructor(ai, modelParams, chromeAdapter, requestOptions) {
2070
2095
  super(ai, modelParams.model);
2096
+ this.chromeAdapter = chromeAdapter;
2071
2097
  this.generationConfig = modelParams.generationConfig || {};
2072
2098
  this.safetySettings = modelParams.safetySettings || [];
2073
2099
  this.tools = modelParams.tools;
@@ -2081,7 +2107,7 @@ class GenerativeModel extends AIModel {
2081
2107
  */
2082
2108
  async generateContent(request) {
2083
2109
  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);
2110
+ 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.chromeAdapter, this.requestOptions);
2085
2111
  }
2086
2112
  /**
2087
2113
  * Makes a single streaming call to the model
@@ -2091,23 +2117,27 @@ class GenerativeModel extends AIModel {
2091
2117
  */
2092
2118
  async generateContentStream(request) {
2093
2119
  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);
2120
+ 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.chromeAdapter, this.requestOptions);
2095
2121
  }
2096
2122
  /**
2097
2123
  * Gets a new {@link ChatSession} instance which can be used for
2098
2124
  * multi-turn chats.
2099
2125
  */
2100
2126
  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);
2127
+ return new ChatSession(this._apiSettings, this.model, this.chromeAdapter, Object.assign({ tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, generationConfig: this.generationConfig, safetySettings: this.safetySettings }, startChatParams), this.requestOptions);
2102
2128
  }
2103
2129
  /**
2104
2130
  * Counts the tokens in the provided request.
2105
2131
  */
2106
2132
  async countTokens(request) {
2107
2133
  const formattedParams = formatGenerateContentInput(request);
2108
- return countTokens(this._apiSettings, this.model, formattedParams);
2134
+ return countTokens(this._apiSettings, this.model, formattedParams, this.chromeAdapter);
2109
2135
  }
2110
2136
  }
2137
+ /**
2138
+ * Defines the name of the default in-cloud model to use for hybrid inference.
2139
+ */
2140
+ GenerativeModel.DEFAULT_HYBRID_IN_CLOUD_MODEL = 'gemini-2.0-flash-lite';
2111
2141
 
2112
2142
  /**
2113
2143
  * @license
@@ -2216,6 +2246,277 @@ class ImagenModel extends AIModel {
2216
2246
  }
2217
2247
  }
2218
2248
 
2249
+ var Availability;
2250
+ (function (Availability) {
2251
+ Availability["unavailable"] = "unavailable";
2252
+ Availability["downloadable"] = "downloadable";
2253
+ Availability["downloading"] = "downloading";
2254
+ Availability["available"] = "available";
2255
+ })(Availability || (Availability = {}));
2256
+
2257
+ /**
2258
+ * @license
2259
+ * Copyright 2025 Google LLC
2260
+ *
2261
+ * Licensed under the Apache License, Version 2.0 (the "License");
2262
+ * you may not use this file except in compliance with the License.
2263
+ * You may obtain a copy of the License at
2264
+ *
2265
+ * http://www.apache.org/licenses/LICENSE-2.0
2266
+ *
2267
+ * Unless required by applicable law or agreed to in writing, software
2268
+ * distributed under the License is distributed on an "AS IS" BASIS,
2269
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2270
+ * See the License for the specific language governing permissions and
2271
+ * limitations under the License.
2272
+ */
2273
+ /**
2274
+ * Defines an inference "backend" that uses Chrome's on-device model,
2275
+ * and encapsulates logic for detecting when on-device is possible.
2276
+ */
2277
+ class ChromeAdapter {
2278
+ constructor(languageModelProvider, mode, onDeviceParams = {
2279
+ createOptions: {
2280
+ // Defaults to support image inputs for convenience.
2281
+ expectedInputs: [{ type: 'image' }]
2282
+ }
2283
+ }) {
2284
+ this.languageModelProvider = languageModelProvider;
2285
+ this.mode = mode;
2286
+ this.onDeviceParams = onDeviceParams;
2287
+ this.isDownloading = false;
2288
+ }
2289
+ /**
2290
+ * Checks if a given request can be made on-device.
2291
+ *
2292
+ * <ol>Encapsulates a few concerns:
2293
+ * <li>the mode</li>
2294
+ * <li>API existence</li>
2295
+ * <li>prompt formatting</li>
2296
+ * <li>model availability, including triggering download if necessary</li>
2297
+ * </ol>
2298
+ *
2299
+ * <p>Pros: callers needn't be concerned with details of on-device availability.</p>
2300
+ * <p>Cons: this method spans a few concerns and splits request validation from usage.
2301
+ * If instance variables weren't already part of the API, we could consider a better
2302
+ * separation of concerns.</p>
2303
+ */
2304
+ async isAvailable(request) {
2305
+ if (!this.mode) {
2306
+ logger.debug(`On-device inference unavailable because mode is undefined.`);
2307
+ return false;
2308
+ }
2309
+ if (this.mode === 'only_in_cloud') {
2310
+ logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
2311
+ return false;
2312
+ }
2313
+ // Triggers out-of-band download so model will eventually become available.
2314
+ const availability = await this.downloadIfAvailable();
2315
+ if (this.mode === 'only_on_device') {
2316
+ return true;
2317
+ }
2318
+ // Applies prefer_on_device logic.
2319
+ if (availability !== Availability.available) {
2320
+ logger.debug(`On-device inference unavailable because availability is "${availability}".`);
2321
+ return false;
2322
+ }
2323
+ if (!ChromeAdapter.isOnDeviceRequest(request)) {
2324
+ logger.debug(`On-device inference unavailable because request is incompatible.`);
2325
+ return false;
2326
+ }
2327
+ return true;
2328
+ }
2329
+ /**
2330
+ * Generates content on device.
2331
+ *
2332
+ * <p>This is comparable to {@link GenerativeModel.generateContent} for generating content in
2333
+ * Cloud.</p>
2334
+ * @param request - a standard Vertex {@link GenerateContentRequest}
2335
+ * @returns {@link Response}, so we can reuse common response formatting.
2336
+ */
2337
+ async generateContent(request) {
2338
+ const session = await this.createSession();
2339
+ const contents = await Promise.all(request.contents.map(ChromeAdapter.toLanguageModelMessage));
2340
+ const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
2341
+ return ChromeAdapter.toResponse(text);
2342
+ }
2343
+ /**
2344
+ * Generates content stream on device.
2345
+ *
2346
+ * <p>This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
2347
+ * Cloud.</p>
2348
+ * @param request - a standard Vertex {@link GenerateContentRequest}
2349
+ * @returns {@link Response}, so we can reuse common response formatting.
2350
+ */
2351
+ async generateContentStream(request) {
2352
+ const session = await this.createSession();
2353
+ const contents = await Promise.all(request.contents.map(ChromeAdapter.toLanguageModelMessage));
2354
+ const stream = await session.promptStreaming(contents, this.onDeviceParams.promptOptions);
2355
+ return ChromeAdapter.toStreamResponse(stream);
2356
+ }
2357
+ async countTokens(_request) {
2358
+ throw new AIError("request-error" /* AIErrorCode.REQUEST_ERROR */, 'Count Tokens is not yet available for on-device model.');
2359
+ }
2360
+ /**
2361
+ * Asserts inference for the given request can be performed by an on-device model.
2362
+ */
2363
+ static isOnDeviceRequest(request) {
2364
+ // Returns false if the prompt is empty.
2365
+ if (request.contents.length === 0) {
2366
+ logger.debug('Empty prompt rejected for on-device inference.');
2367
+ return false;
2368
+ }
2369
+ for (const content of request.contents) {
2370
+ if (content.role === 'function') {
2371
+ logger.debug(`"Function" role rejected for on-device inference.`);
2372
+ return false;
2373
+ }
2374
+ // Returns false if request contains an image with an unsupported mime type.
2375
+ for (const part of content.parts) {
2376
+ if (part.inlineData &&
2377
+ ChromeAdapter.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
2378
+ logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
2379
+ return false;
2380
+ }
2381
+ }
2382
+ }
2383
+ return true;
2384
+ }
2385
+ /**
2386
+ * Encapsulates logic to get availability and download a model if one is downloadable.
2387
+ */
2388
+ async downloadIfAvailable() {
2389
+ var _a;
2390
+ const availability = await ((_a = this.languageModelProvider) === null || _a === void 0 ? void 0 : _a.availability(this.onDeviceParams.createOptions));
2391
+ if (availability === Availability.downloadable) {
2392
+ this.download();
2393
+ }
2394
+ return availability;
2395
+ }
2396
+ /**
2397
+ * Triggers out-of-band download of an on-device model.
2398
+ *
2399
+ * <p>Chrome only downloads models as needed. Chrome knows a model is needed when code calls
2400
+ * LanguageModel.create.</p>
2401
+ *
2402
+ * <p>Since Chrome manages the download, the SDK can only avoid redundant download requests by
2403
+ * tracking if a download has previously been requested.</p>
2404
+ */
2405
+ download() {
2406
+ var _a;
2407
+ if (this.isDownloading) {
2408
+ return;
2409
+ }
2410
+ this.isDownloading = true;
2411
+ this.downloadPromise = (_a = this.languageModelProvider) === null || _a === void 0 ? void 0 : _a.create(this.onDeviceParams.createOptions).then(() => {
2412
+ this.isDownloading = false;
2413
+ });
2414
+ }
2415
+ /**
2416
+ * Converts Vertex {@link Content} object to a Chrome {@link LanguageModelMessage} object.
2417
+ */
2418
+ static async toLanguageModelMessage(content) {
2419
+ const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapter.toLanguageModelMessageContent));
2420
+ return {
2421
+ role: ChromeAdapter.toLanguageModelMessageRole(content.role),
2422
+ content: languageModelMessageContents
2423
+ };
2424
+ }
2425
+ /**
2426
+ * Converts a Vertex Part object to a Chrome LanguageModelMessageContent object.
2427
+ */
2428
+ static async toLanguageModelMessageContent(part) {
2429
+ if (part.text) {
2430
+ return {
2431
+ type: 'text',
2432
+ value: part.text
2433
+ };
2434
+ }
2435
+ else if (part.inlineData) {
2436
+ const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
2437
+ const imageBlob = await formattedImageContent.blob();
2438
+ const imageBitmap = await createImageBitmap(imageBlob);
2439
+ return {
2440
+ type: 'image',
2441
+ value: imageBitmap
2442
+ };
2443
+ }
2444
+ // Assumes contents have been verified to contain only a single TextPart.
2445
+ // TODO: support other input types
2446
+ throw new Error('Not yet implemented');
2447
+ }
2448
+ /**
2449
+ * Converts a Vertex {@link Role} string to a {@link LanguageModelMessageRole} string.
2450
+ */
2451
+ static toLanguageModelMessageRole(role) {
2452
+ // Assumes 'function' rule has been filtered by isOnDeviceRequest
2453
+ return role === 'model' ? 'assistant' : 'user';
2454
+ }
2455
+ /**
2456
+ * Abstracts Chrome session creation.
2457
+ *
2458
+ * <p>Chrome uses a multi-turn session for all inference. Vertex uses single-turn for all
2459
+ * inference. To map the Vertex API to Chrome's API, the SDK creates a new session for all
2460
+ * inference.</p>
2461
+ *
2462
+ * <p>Chrome will remove a model from memory if it's no longer in use, so this method ensures a
2463
+ * new session is created before an old session is destroyed.</p>
2464
+ */
2465
+ async createSession() {
2466
+ if (!this.languageModelProvider) {
2467
+ throw new AIError("request-error" /* AIErrorCode.REQUEST_ERROR */, 'Chrome AI requested for unsupported browser version.');
2468
+ }
2469
+ const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
2470
+ if (this.oldSession) {
2471
+ this.oldSession.destroy();
2472
+ }
2473
+ // Holds session reference, so model isn't unloaded from memory.
2474
+ this.oldSession = newSession;
2475
+ return newSession;
2476
+ }
2477
+ /**
2478
+ * Formats string returned by Chrome as a {@link Response} returned by Vertex.
2479
+ */
2480
+ static toResponse(text) {
2481
+ return {
2482
+ json: async () => ({
2483
+ candidates: [
2484
+ {
2485
+ content: {
2486
+ parts: [{ text }]
2487
+ }
2488
+ }
2489
+ ]
2490
+ })
2491
+ };
2492
+ }
2493
+ /**
2494
+ * Formats string stream returned by Chrome as SSE returned by Vertex.
2495
+ */
2496
+ static toStreamResponse(stream) {
2497
+ const encoder = new TextEncoder();
2498
+ return {
2499
+ body: stream.pipeThrough(new TransformStream({
2500
+ transform(chunk, controller) {
2501
+ const json = JSON.stringify({
2502
+ candidates: [
2503
+ {
2504
+ content: {
2505
+ role: 'model',
2506
+ parts: [{ text: chunk }]
2507
+ }
2508
+ }
2509
+ ]
2510
+ });
2511
+ controller.enqueue(encoder.encode(`data: ${json}\n\n`));
2512
+ }
2513
+ }))
2514
+ };
2515
+ }
2516
+ }
2517
+ // Visible for testing
2518
+ ChromeAdapter.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
2519
+
2219
2520
  /**
2220
2521
  * @license
2221
2522
  * Copyright 2024 Google LLC
@@ -2571,10 +2872,21 @@ function getAI(app = getApp(), options = { backend: new GoogleAIBackend() }) {
2571
2872
  * @public
2572
2873
  */
2573
2874
  function getGenerativeModel(ai, modelParams, requestOptions) {
2574
- if (!modelParams.model) {
2875
+ // Uses the existence of HybridParams.mode to clarify the type of the modelParams input.
2876
+ const hybridParams = modelParams;
2877
+ let inCloudParams;
2878
+ if (hybridParams.mode) {
2879
+ inCloudParams = hybridParams.inCloudParams || {
2880
+ model: GenerativeModel.DEFAULT_HYBRID_IN_CLOUD_MODEL
2881
+ };
2882
+ }
2883
+ else {
2884
+ inCloudParams = modelParams;
2885
+ }
2886
+ if (!inCloudParams.model) {
2575
2887
  throw new AIError("no-model" /* AIErrorCode.NO_MODEL */, `Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })`);
2576
2888
  }
2577
- return new GenerativeModel(ai, modelParams, requestOptions);
2889
+ return new GenerativeModel(ai, inCloudParams, new ChromeAdapter(window.LanguageModel, hybridParams.mode, hybridParams.onDeviceParams), requestOptions);
2578
2890
  }
2579
2891
  /**
2580
2892
  * Returns an {@link ImagenModel} class with methods for using Imagen.