@google/genai 1.41.0 → 1.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1328,6 +1328,18 @@ var Environment;
1328
1328
  */
1329
1329
  Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER";
1330
1330
  })(Environment || (Environment = {}));
1331
+ /** Enum representing the Vertex embedding API to use. */
1332
+ var EmbeddingApiType;
1333
+ (function (EmbeddingApiType) {
1334
+ /**
1335
+ * predict API endpoint (default)
1336
+ */
1337
+ EmbeddingApiType["PREDICT"] = "PREDICT";
1338
+ /**
1339
+ * embedContent API Endpoint
1340
+ */
1341
+ EmbeddingApiType["EMBED_CONTENT"] = "EMBED_CONTENT";
1342
+ })(EmbeddingApiType || (EmbeddingApiType = {}));
1331
1343
  /** Enum that controls the safety filter level for objectionable content. */
1332
1344
  var SafetyFilterLevel;
1333
1345
  (function (SafetyFilterLevel) {
@@ -3359,6 +3371,10 @@ function tJobState(state) {
3359
3371
  return stateString;
3360
3372
  }
3361
3373
  }
3374
+ function tIsVertexEmbedContentModel(model) {
3375
+ return ((model.includes('gemini') && model !== 'gemini-embedding-001') ||
3376
+ model.includes('maas'));
3377
+ }
3362
3378
 
3363
3379
  /**
3364
3380
  * @license
@@ -6931,7 +6947,7 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
6931
6947
  const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
6932
6948
  const USER_AGENT_HEADER = 'User-Agent';
6933
6949
  const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
6934
- const SDK_VERSION = '1.41.0'; // x-release-please-version
6950
+ const SDK_VERSION = '1.42.0'; // x-release-please-version
6935
6951
  const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
6936
6952
  const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
6937
6953
  const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
@@ -10659,6 +10675,13 @@ class BaseGeminiNextGenAPIClient {
10659
10675
  (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
10660
10676
  return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
10661
10677
  }
10678
+ else if (typeof body === 'object' &&
10679
+ headers.values.get('content-type') === 'application/x-www-form-urlencoded') {
10680
+ return {
10681
+ bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
10682
+ body: this.stringifyQuery(body),
10683
+ };
10684
+ }
10662
10685
  else {
10663
10686
  return this.encoder({ body, headers });
10664
10687
  }
@@ -12162,33 +12185,103 @@ function embedContentConfigToMldev(fromObject, parentObject, _rootObject) {
12162
12185
  }
12163
12186
  return toObject;
12164
12187
  }
12165
- function embedContentConfigToVertex(fromObject, parentObject, _rootObject) {
12188
+ function embedContentConfigToVertex(fromObject, parentObject, rootObject) {
12166
12189
  const toObject = {};
12167
- const fromTaskType = getValueByPath(fromObject, ['taskType']);
12168
- if (parentObject !== undefined && fromTaskType != null) {
12169
- setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType);
12190
+ let discriminatorTaskType = getValueByPath(rootObject, [
12191
+ 'embeddingApiType',
12192
+ ]);
12193
+ if (discriminatorTaskType === undefined) {
12194
+ discriminatorTaskType = 'PREDICT';
12170
12195
  }
12171
- const fromTitle = getValueByPath(fromObject, ['title']);
12172
- if (parentObject !== undefined && fromTitle != null) {
12173
- setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);
12196
+ if (discriminatorTaskType === 'PREDICT') {
12197
+ const fromTaskType = getValueByPath(fromObject, ['taskType']);
12198
+ if (parentObject !== undefined && fromTaskType != null) {
12199
+ setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType);
12200
+ }
12174
12201
  }
12175
- const fromOutputDimensionality = getValueByPath(fromObject, [
12176
- 'outputDimensionality',
12202
+ else if (discriminatorTaskType === 'EMBED_CONTENT') {
12203
+ const fromTaskType = getValueByPath(fromObject, ['taskType']);
12204
+ if (parentObject !== undefined && fromTaskType != null) {
12205
+ setValueByPath(parentObject, ['taskType'], fromTaskType);
12206
+ }
12207
+ }
12208
+ let discriminatorTitle = getValueByPath(rootObject, [
12209
+ 'embeddingApiType',
12177
12210
  ]);
12178
- if (parentObject !== undefined && fromOutputDimensionality != null) {
12179
- setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality);
12211
+ if (discriminatorTitle === undefined) {
12212
+ discriminatorTitle = 'PREDICT';
12180
12213
  }
12181
- const fromMimeType = getValueByPath(fromObject, ['mimeType']);
12182
- if (parentObject !== undefined && fromMimeType != null) {
12183
- setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType);
12214
+ if (discriminatorTitle === 'PREDICT') {
12215
+ const fromTitle = getValueByPath(fromObject, ['title']);
12216
+ if (parentObject !== undefined && fromTitle != null) {
12217
+ setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);
12218
+ }
12219
+ }
12220
+ else if (discriminatorTitle === 'EMBED_CONTENT') {
12221
+ const fromTitle = getValueByPath(fromObject, ['title']);
12222
+ if (parentObject !== undefined && fromTitle != null) {
12223
+ setValueByPath(parentObject, ['title'], fromTitle);
12224
+ }
12225
+ }
12226
+ let discriminatorOutputDimensionality = getValueByPath(rootObject, [
12227
+ 'embeddingApiType',
12228
+ ]);
12229
+ if (discriminatorOutputDimensionality === undefined) {
12230
+ discriminatorOutputDimensionality = 'PREDICT';
12231
+ }
12232
+ if (discriminatorOutputDimensionality === 'PREDICT') {
12233
+ const fromOutputDimensionality = getValueByPath(fromObject, [
12234
+ 'outputDimensionality',
12235
+ ]);
12236
+ if (parentObject !== undefined && fromOutputDimensionality != null) {
12237
+ setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality);
12238
+ }
12239
+ }
12240
+ else if (discriminatorOutputDimensionality === 'EMBED_CONTENT') {
12241
+ const fromOutputDimensionality = getValueByPath(fromObject, [
12242
+ 'outputDimensionality',
12243
+ ]);
12244
+ if (parentObject !== undefined && fromOutputDimensionality != null) {
12245
+ setValueByPath(parentObject, ['outputDimensionality'], fromOutputDimensionality);
12246
+ }
12184
12247
  }
12185
- const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']);
12186
- if (parentObject !== undefined && fromAutoTruncate != null) {
12187
- setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate);
12248
+ let discriminatorMimeType = getValueByPath(rootObject, [
12249
+ 'embeddingApiType',
12250
+ ]);
12251
+ if (discriminatorMimeType === undefined) {
12252
+ discriminatorMimeType = 'PREDICT';
12253
+ }
12254
+ if (discriminatorMimeType === 'PREDICT') {
12255
+ const fromMimeType = getValueByPath(fromObject, ['mimeType']);
12256
+ if (parentObject !== undefined && fromMimeType != null) {
12257
+ setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType);
12258
+ }
12259
+ }
12260
+ let discriminatorAutoTruncate = getValueByPath(rootObject, [
12261
+ 'embeddingApiType',
12262
+ ]);
12263
+ if (discriminatorAutoTruncate === undefined) {
12264
+ discriminatorAutoTruncate = 'PREDICT';
12265
+ }
12266
+ if (discriminatorAutoTruncate === 'PREDICT') {
12267
+ const fromAutoTruncate = getValueByPath(fromObject, [
12268
+ 'autoTruncate',
12269
+ ]);
12270
+ if (parentObject !== undefined && fromAutoTruncate != null) {
12271
+ setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate);
12272
+ }
12273
+ }
12274
+ else if (discriminatorAutoTruncate === 'EMBED_CONTENT') {
12275
+ const fromAutoTruncate = getValueByPath(fromObject, [
12276
+ 'autoTruncate',
12277
+ ]);
12278
+ if (parentObject !== undefined && fromAutoTruncate != null) {
12279
+ setValueByPath(parentObject, ['autoTruncate'], fromAutoTruncate);
12280
+ }
12188
12281
  }
12189
12282
  return toObject;
12190
12283
  }
12191
- function embedContentParametersToMldev(apiClient, fromObject, rootObject) {
12284
+ function embedContentParametersPrivateToMldev(apiClient, fromObject, rootObject) {
12192
12285
  const toObject = {};
12193
12286
  const fromModel = getValueByPath(fromObject, ['model']);
12194
12287
  if (fromModel != null) {
@@ -12204,6 +12297,10 @@ function embedContentParametersToMldev(apiClient, fromObject, rootObject) {
12204
12297
  }
12205
12298
  setValueByPath(toObject, ['requests[]', 'content'], transformedList);
12206
12299
  }
12300
+ const fromContent = getValueByPath(fromObject, ['content']);
12301
+ if (fromContent != null) {
12302
+ contentToMldev$1(tContent(fromContent));
12303
+ }
12207
12304
  const fromConfig = getValueByPath(fromObject, ['config']);
12208
12305
  if (fromConfig != null) {
12209
12306
  embedContentConfigToMldev(fromConfig, toObject);
@@ -12214,25 +12311,45 @@ function embedContentParametersToMldev(apiClient, fromObject, rootObject) {
12214
12311
  }
12215
12312
  return toObject;
12216
12313
  }
12217
- function embedContentParametersToVertex(apiClient, fromObject, rootObject) {
12314
+ function embedContentParametersPrivateToVertex(apiClient, fromObject, rootObject) {
12218
12315
  const toObject = {};
12219
12316
  const fromModel = getValueByPath(fromObject, ['model']);
12220
12317
  if (fromModel != null) {
12221
12318
  setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel));
12222
12319
  }
12223
- const fromContents = getValueByPath(fromObject, ['contents']);
12224
- if (fromContents != null) {
12225
- let transformedList = tContentsForEmbed(apiClient, fromContents);
12226
- if (Array.isArray(transformedList)) {
12227
- transformedList = transformedList.map((item) => {
12228
- return item;
12229
- });
12320
+ let discriminatorContents = getValueByPath(rootObject, [
12321
+ 'embeddingApiType',
12322
+ ]);
12323
+ if (discriminatorContents === undefined) {
12324
+ discriminatorContents = 'PREDICT';
12325
+ }
12326
+ if (discriminatorContents === 'PREDICT') {
12327
+ const fromContents = getValueByPath(fromObject, ['contents']);
12328
+ if (fromContents != null) {
12329
+ let transformedList = tContentsForEmbed(apiClient, fromContents);
12330
+ if (Array.isArray(transformedList)) {
12331
+ transformedList = transformedList.map((item) => {
12332
+ return item;
12333
+ });
12334
+ }
12335
+ setValueByPath(toObject, ['instances[]', 'content'], transformedList);
12336
+ }
12337
+ }
12338
+ let discriminatorContent = getValueByPath(rootObject, [
12339
+ 'embeddingApiType',
12340
+ ]);
12341
+ if (discriminatorContent === undefined) {
12342
+ discriminatorContent = 'PREDICT';
12343
+ }
12344
+ if (discriminatorContent === 'EMBED_CONTENT') {
12345
+ const fromContent = getValueByPath(fromObject, ['content']);
12346
+ if (fromContent != null) {
12347
+ setValueByPath(toObject, ['content'], tContent(fromContent));
12230
12348
  }
12231
- setValueByPath(toObject, ['instances[]', 'content'], transformedList);
12232
12349
  }
12233
12350
  const fromConfig = getValueByPath(fromObject, ['config']);
12234
12351
  if (fromConfig != null) {
12235
- embedContentConfigToVertex(fromConfig, toObject);
12352
+ embedContentConfigToVertex(fromConfig, toObject, rootObject);
12236
12353
  }
12237
12354
  return toObject;
12238
12355
  }
@@ -12285,6 +12402,24 @@ function embedContentResponseFromVertex(fromObject, rootObject) {
12285
12402
  if (fromMetadata != null) {
12286
12403
  setValueByPath(toObject, ['metadata'], fromMetadata);
12287
12404
  }
12405
+ if (rootObject &&
12406
+ getValueByPath(rootObject, ['embeddingApiType']) === 'EMBED_CONTENT') {
12407
+ const embedding = getValueByPath(fromObject, ['embedding']);
12408
+ const usageMetadata = getValueByPath(fromObject, ['usageMetadata']);
12409
+ const truncated = getValueByPath(fromObject, ['truncated']);
12410
+ if (embedding) {
12411
+ const stats = {};
12412
+ if (usageMetadata &&
12413
+ usageMetadata['promptTokenCount']) {
12414
+ stats.tokenCount = usageMetadata['promptTokenCount'];
12415
+ }
12416
+ if (truncated) {
12417
+ stats.truncated = truncated;
12418
+ }
12419
+ embedding.statistics = stats;
12420
+ setValueByPath(toObject, ['embeddings'], [embedding]);
12421
+ }
12422
+ }
12288
12423
  return toObject;
12289
12424
  }
12290
12425
  function endpointFromVertex(fromObject, _rootObject) {
@@ -15833,6 +15968,47 @@ class Models extends BaseModule {
15833
15968
  constructor(apiClient) {
15834
15969
  super();
15835
15970
  this.apiClient = apiClient;
15971
+ /**
15972
+ * Calculates embeddings for the given contents.
15973
+ *
15974
+ * @param params - The parameters for embedding contents.
15975
+ * @return The response from the API.
15976
+ *
15977
+ * @example
15978
+ * ```ts
15979
+ * const response = await ai.models.embedContent({
15980
+ * model: 'text-embedding-004',
15981
+ * contents: [
15982
+ * 'What is your name?',
15983
+ * 'What is your favorite color?',
15984
+ * ],
15985
+ * config: {
15986
+ * outputDimensionality: 64,
15987
+ * },
15988
+ * });
15989
+ * console.log(response);
15990
+ * ```
15991
+ */
15992
+ this.embedContent = async (params) => {
15993
+ if (!this.apiClient.isVertexAI()) {
15994
+ return await this.embedContentInternal(params);
15995
+ }
15996
+ const isVertexEmbedContentModel = (params.model.includes('gemini') &&
15997
+ params.model !== 'gemini-embedding-001') ||
15998
+ params.model.includes('maas');
15999
+ if (isVertexEmbedContentModel) {
16000
+ const contents = tContents(params.contents);
16001
+ if (contents.length > 1) {
16002
+ throw new Error('The embedContent API for this model only supports one content at a time.');
16003
+ }
16004
+ const paramsPrivate = Object.assign(Object.assign({}, params), { content: contents[0], embeddingApiType: EmbeddingApiType.EMBED_CONTENT });
16005
+ return await this.embedContentInternal(paramsPrivate);
16006
+ }
16007
+ else {
16008
+ const paramsPrivate = Object.assign(Object.assign({}, params), { embeddingApiType: EmbeddingApiType.PREDICT });
16009
+ return await this.embedContentInternal(paramsPrivate);
16010
+ }
16011
+ };
15836
16012
  /**
15837
16013
  * Makes an API request to generate content with a given model.
15838
16014
  *
@@ -16520,14 +16696,17 @@ class Models extends BaseModule {
16520
16696
  * console.log(response);
16521
16697
  * ```
16522
16698
  */
16523
- async embedContent(params) {
16699
+ async embedContentInternal(params) {
16524
16700
  var _a, _b, _c, _d;
16525
16701
  let response;
16526
16702
  let path = '';
16527
16703
  let queryParams = {};
16528
16704
  if (this.apiClient.isVertexAI()) {
16529
- const body = embedContentParametersToVertex(this.apiClient, params);
16530
- path = formatMap('{model}:predict', body['_url']);
16705
+ const body = embedContentParametersPrivateToVertex(this.apiClient, params, params);
16706
+ const endpointUrl = tIsVertexEmbedContentModel(params.model)
16707
+ ? '{model}:embedContent'
16708
+ : '{model}:predict';
16709
+ path = formatMap(endpointUrl, body['_url']);
16531
16710
  queryParams = body['_query'];
16532
16711
  delete body['_url'];
16533
16712
  delete body['_query'];
@@ -16550,14 +16729,14 @@ class Models extends BaseModule {
16550
16729
  });
16551
16730
  });
16552
16731
  return response.then((apiResponse) => {
16553
- const resp = embedContentResponseFromVertex(apiResponse);
16732
+ const resp = embedContentResponseFromVertex(apiResponse, params);
16554
16733
  const typedResp = new EmbedContentResponse();
16555
16734
  Object.assign(typedResp, resp);
16556
16735
  return typedResp;
16557
16736
  });
16558
16737
  }
16559
16738
  else {
16560
- const body = embedContentParametersToMldev(this.apiClient, params);
16739
+ const body = embedContentParametersPrivateToMldev(this.apiClient, params);
16561
16740
  path = formatMap('{model}:batchEmbedContents', body['_url']);
16562
16741
  queryParams = body['_query'];
16563
16742
  delete body['_url'];
@@ -19514,5 +19693,5 @@ class GoogleGenAI {
19514
19693
  }
19515
19694
  }
19516
19695
 
19517
- export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, CancelTuningJobResponse, Chat, Chats, ComputeTokensResponse, ContentReferenceImage, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DocumentState, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpElementLocation, HttpResponse, ImagePromptLanguage, ImportFileOperation, ImportFileResponse, InlinedEmbedContentResponse, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PartMediaResolutionLevel, PersonGeneration, PhishBlockThreshold, RawReferenceImage, RecontextImageResponse, RegisterFilesResponse, ReplayResponse, ResourceScope, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, SingleEmbedContentResponse, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, ThinkingLevel, Tokens, TrafficType, TuningMethod, TuningMode, TuningTask, TurnCompleteReason, TurnCoverage, Type, UploadToFileSearchStoreOperation, UploadToFileSearchStoreResponse, UploadToFileSearchStoreResumableResponse, UpscaleImageResponse, UrlRetrievalStatus, VadSignalType, VideoCompressionQuality, VideoGenerationMaskMode, VideoGenerationReferenceType, VoiceActivityType, createFunctionResponsePartFromBase64, createFunctionResponsePartFromUri, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls };
19696
+ export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, CancelTuningJobResponse, Chat, Chats, ComputeTokensResponse, ContentReferenceImage, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DocumentState, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EmbeddingApiType, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpElementLocation, HttpResponse, ImagePromptLanguage, ImportFileOperation, ImportFileResponse, InlinedEmbedContentResponse, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PartMediaResolutionLevel, PersonGeneration, PhishBlockThreshold, RawReferenceImage, RecontextImageResponse, RegisterFilesResponse, ReplayResponse, ResourceScope, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, SingleEmbedContentResponse, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, ThinkingLevel, Tokens, TrafficType, TuningMethod, TuningMode, TuningTask, TurnCompleteReason, TurnCoverage, Type, UploadToFileSearchStoreOperation, UploadToFileSearchStoreResponse, UploadToFileSearchStoreResumableResponse, UpscaleImageResponse, UrlRetrievalStatus, VadSignalType, VideoCompressionQuality, VideoGenerationMaskMode, VideoGenerationReferenceType, VoiceActivityType, createFunctionResponsePartFromBase64, createFunctionResponsePartFromUri, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls };
19518
19697
  //# sourceMappingURL=index.mjs.map