@google/genai 1.8.0 → 1.9.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.
@@ -1,6 +1,5 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
3
  var googleAuthLibrary = require('google-auth-library');
5
4
  var fs = require('fs');
6
5
  var node_stream = require('node:stream');
@@ -818,11 +817,38 @@ exports.PersonGeneration = void 0;
818
817
  /** Enum that specifies the language of the text in the prompt. */
819
818
  exports.ImagePromptLanguage = void 0;
820
819
  (function (ImagePromptLanguage) {
820
+ /**
821
+ * Auto-detect the language.
822
+ */
821
823
  ImagePromptLanguage["auto"] = "auto";
824
+ /**
825
+ * English
826
+ */
822
827
  ImagePromptLanguage["en"] = "en";
828
+ /**
829
+ * Japanese
830
+ */
823
831
  ImagePromptLanguage["ja"] = "ja";
832
+ /**
833
+ * Korean
834
+ */
824
835
  ImagePromptLanguage["ko"] = "ko";
836
+ /**
837
+ * Hindi
838
+ */
825
839
  ImagePromptLanguage["hi"] = "hi";
840
+ /**
841
+ * Chinese
842
+ */
843
+ ImagePromptLanguage["zh"] = "zh";
844
+ /**
845
+ * Portuguese
846
+ */
847
+ ImagePromptLanguage["pt"] = "pt";
848
+ /**
849
+ * Spanish
850
+ */
851
+ ImagePromptLanguage["es"] = "es";
826
852
  })(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {}));
827
853
  /** Enum representing the mask mode of a mask reference image. */
828
854
  exports.MaskReferenceMode = void 0;
@@ -1923,133 +1949,12 @@ function tContents(origin) {
1923
1949
  }
1924
1950
  return result;
1925
1951
  }
1926
- // The fields that are supported by JSONSchema. Must be kept in sync with the
1927
- // JSONSchema interface above.
1928
- const supportedJsonSchemaFields = new Set([
1929
- 'type',
1930
- 'format',
1931
- 'title',
1932
- 'description',
1933
- 'default',
1934
- 'items',
1935
- 'minItems',
1936
- 'maxItems',
1937
- 'enum',
1938
- 'properties',
1939
- 'required',
1940
- 'minProperties',
1941
- 'maxProperties',
1942
- 'minimum',
1943
- 'maximum',
1944
- 'minLength',
1945
- 'maxLength',
1946
- 'pattern',
1947
- 'anyOf',
1948
- 'propertyOrdering',
1949
- ]);
1950
- const jsonSchemaTypeValidator = zod.z.enum([
1951
- 'string',
1952
- 'number',
1953
- 'integer',
1954
- 'object',
1955
- 'array',
1956
- 'boolean',
1957
- 'null',
1958
- ]);
1959
- // Handles all types and arrays of all types.
1960
- const schemaTypeUnion = zod.z.union([
1961
- jsonSchemaTypeValidator,
1962
- zod.z.array(jsonSchemaTypeValidator),
1963
- ]);
1964
- /**
1965
- * Creates a zod validator for JSONSchema.
1966
- *
1967
- * @param strictMode Whether to enable strict mode, default to true. When
1968
- * strict mode is enabled, the zod validator will throw error if there
1969
- * are unrecognized fields in the input data. If strict mode is
1970
- * disabled, the zod validator will ignore the unrecognized fields, only
1971
- * populate the fields that are listed in the JSONSchema. Regardless of
1972
- * the mode the type mismatch will always result in an error, for example
1973
- * items field should be a single JSONSchema, but for tuple type it would
1974
- * be an array of JSONSchema, this will always result in an error.
1975
- * @return The zod validator for JSONSchema.
1976
- */
1977
- function createJsonSchemaValidator(strictMode = true) {
1978
- const jsonSchemaValidator = zod.z.lazy(() => {
1979
- // Define the base object shape *inside* the z.lazy callback
1980
- const baseShape = zod.z.object({
1981
- // --- Type ---
1982
- type: schemaTypeUnion.optional(),
1983
- // --- Annotations ---
1984
- format: zod.z.string().optional(),
1985
- title: zod.z.string().optional(),
1986
- description: zod.z.string().optional(),
1987
- default: zod.z.unknown().optional(),
1988
- // --- Array Validations ---
1989
- items: jsonSchemaValidator.optional(),
1990
- minItems: zod.z.coerce.string().optional(),
1991
- maxItems: zod.z.coerce.string().optional(),
1992
- // --- Generic Validations ---
1993
- enum: zod.z.array(zod.z.unknown()).optional(),
1994
- // --- Object Validations ---
1995
- properties: zod.z.record(zod.z.string(), jsonSchemaValidator).optional(),
1996
- required: zod.z.array(zod.z.string()).optional(),
1997
- minProperties: zod.z.coerce.string().optional(),
1998
- maxProperties: zod.z.coerce.string().optional(),
1999
- propertyOrdering: zod.z.array(zod.z.string()).optional(),
2000
- // --- Numeric Validations ---
2001
- minimum: zod.z.number().optional(),
2002
- maximum: zod.z.number().optional(),
2003
- // --- String Validations ---
2004
- minLength: zod.z.coerce.string().optional(),
2005
- maxLength: zod.z.coerce.string().optional(),
2006
- pattern: zod.z.string().optional(),
2007
- // --- Schema Composition ---
2008
- anyOf: zod.z.array(jsonSchemaValidator).optional(),
2009
- // --- Additional Properties --- This field is not included in the
2010
- // JSONSchema, will not be communicated to the model, it is here purely
2011
- // for enabling the zod validation strict mode.
2012
- additionalProperties: zod.z.boolean().optional(),
2013
- });
2014
- // Conditionally apply .strict() based on the flag
2015
- return strictMode ? baseShape.strict() : baseShape;
2016
- });
2017
- return jsonSchemaValidator;
2018
- }
2019
1952
  /*
2020
- Handle type field:
2021
- The resulted type field in JSONSchema form zod_to_json_schema can be either
2022
- an array consist of primitive types or a single primitive type.
2023
- This is due to the optimization of zod_to_json_schema, when the types in the
2024
- union are primitive types without any additional specifications,
2025
- zod_to_json_schema will squash the types into an array instead of put them
2026
- in anyOf fields. Otherwise, it will put the types in anyOf fields.
2027
- See the following link for more details:
2028
- https://github.com/zodjs/zod-to-json-schema/blob/main/src/index.ts#L101
2029
- The logic here is trying to undo that optimization, flattening the array of
2030
- types to anyOf fields.
2031
- type field
2032
- |
2033
- ___________________________
2034
- / \
2035
- / \
2036
- / \
2037
- Array Type.*
2038
- / \ |
2039
- Include null. Not included null type = Type.*.
2040
- [null, Type.*, Type.*] multiple types.
2041
- [null, Type.*] [Type.*, Type.*]
2042
- / \
2043
- remove null \
2044
- add nullable = true \
2045
- / \ \
2046
- [Type.*] [Type.*, Type.*] \
2047
- only one type left multiple types left \
2048
- add type = Type.*. \ /
2049
- \ /
2050
- not populate the type field in final result
2051
- and make the types into anyOf fields
2052
- anyOf:[{type: 'Type.*'}, {type: 'Type.*'}];
1953
+ Transform the type field from an array of types to an array of anyOf fields.
1954
+ Example:
1955
+ {type: ['STRING', 'NUMBER']}
1956
+ will be transformed to
1957
+ {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}
2053
1958
  */
2054
1959
  function flattenTypeArrayToAnyOf(typeList, resultingSchema) {
2055
1960
  if (typeList.includes('null')) {
@@ -2195,15 +2100,11 @@ function processJsonSchema(_jsonSchema) {
2195
2100
  // https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7
2196
2101
  // typebox can return unknown, see details in
2197
2102
  // https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35
2103
+ // Note: proper json schemas with the $schema field set never arrive to this
2104
+ // transformer. Schemas with $schema are routed to the equivalent API json
2105
+ // schema field.
2198
2106
  function tSchema(schema) {
2199
- if (Object.keys(schema).includes('$schema')) {
2200
- delete schema['$schema'];
2201
- const validatedJsonSchema = createJsonSchemaValidator().parse(schema);
2202
- return processJsonSchema(validatedJsonSchema);
2203
- }
2204
- else {
2205
- return processJsonSchema(schema);
2206
- }
2107
+ return processJsonSchema(schema);
2207
2108
  }
2208
2109
  function tSpeechConfig(speechConfig) {
2209
2110
  if (typeof speechConfig === 'object') {
@@ -2232,10 +2133,28 @@ function tTool(tool) {
2232
2133
  if (tool.functionDeclarations) {
2233
2134
  for (const functionDeclaration of tool.functionDeclarations) {
2234
2135
  if (functionDeclaration.parameters) {
2235
- functionDeclaration.parameters = tSchema(functionDeclaration.parameters);
2136
+ if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {
2137
+ functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters);
2138
+ }
2139
+ else {
2140
+ if (!functionDeclaration.parametersJsonSchema) {
2141
+ functionDeclaration.parametersJsonSchema =
2142
+ functionDeclaration.parameters;
2143
+ delete functionDeclaration.parameters;
2144
+ }
2145
+ }
2236
2146
  }
2237
2147
  if (functionDeclaration.response) {
2238
- functionDeclaration.response = tSchema(functionDeclaration.response);
2148
+ if (!Object.keys(functionDeclaration.response).includes('$schema')) {
2149
+ functionDeclaration.response = processJsonSchema(functionDeclaration.response);
2150
+ }
2151
+ else {
2152
+ if (!functionDeclaration.responseJsonSchema) {
2153
+ functionDeclaration.responseJsonSchema =
2154
+ functionDeclaration.response;
2155
+ delete functionDeclaration.response;
2156
+ }
2157
+ }
2239
2158
  }
2240
2159
  }
2241
2160
  }
@@ -2440,7 +2359,7 @@ function mcpToGeminiTool(mcpTool, config = {}) {
2440
2359
  const functionDeclaration = {
2441
2360
  name: mcpToolSchema['name'],
2442
2361
  description: mcpToolSchema['description'],
2443
- parameters: processJsonSchema(filterToJsonSchema(mcpToolSchema['inputSchema'])),
2362
+ parametersJsonSchema: mcpToolSchema['inputSchema'],
2444
2363
  };
2445
2364
  if (config.behavior) {
2446
2365
  functionDeclaration['behavior'] = config.behavior;
@@ -2472,53 +2391,6 @@ function mcpToolsToGeminiTool(mcpTools, config = {}) {
2472
2391
  }
2473
2392
  return { functionDeclarations: functionDeclarations };
2474
2393
  }
2475
- // Filters the list schema field to only include fields that are supported by
2476
- // JSONSchema.
2477
- function filterListSchemaField(fieldValue) {
2478
- const listSchemaFieldValue = [];
2479
- for (const listFieldValue of fieldValue) {
2480
- listSchemaFieldValue.push(filterToJsonSchema(listFieldValue));
2481
- }
2482
- return listSchemaFieldValue;
2483
- }
2484
- // Filters the dict schema field to only include fields that are supported by
2485
- // JSONSchema.
2486
- function filterDictSchemaField(fieldValue) {
2487
- const dictSchemaFieldValue = {};
2488
- for (const [key, value] of Object.entries(fieldValue)) {
2489
- const valueRecord = value;
2490
- dictSchemaFieldValue[key] = filterToJsonSchema(valueRecord);
2491
- }
2492
- return dictSchemaFieldValue;
2493
- }
2494
- // Filters the schema to only include fields that are supported by JSONSchema.
2495
- function filterToJsonSchema(schema) {
2496
- const schemaFieldNames = new Set(['items']); // 'additional_properties' to come
2497
- const listSchemaFieldNames = new Set(['anyOf']); // 'one_of', 'all_of', 'not' to come
2498
- const dictSchemaFieldNames = new Set(['properties']); // 'defs' to come
2499
- const filteredSchema = {};
2500
- for (const [fieldName, fieldValue] of Object.entries(schema)) {
2501
- if (schemaFieldNames.has(fieldName)) {
2502
- filteredSchema[fieldName] = filterToJsonSchema(fieldValue);
2503
- }
2504
- else if (listSchemaFieldNames.has(fieldName)) {
2505
- filteredSchema[fieldName] = filterListSchemaField(fieldValue);
2506
- }
2507
- else if (dictSchemaFieldNames.has(fieldName)) {
2508
- filteredSchema[fieldName] = filterDictSchemaField(fieldValue);
2509
- }
2510
- else if (fieldName === 'type') {
2511
- const typeValue = fieldValue.toUpperCase();
2512
- filteredSchema[fieldName] = Object.values(exports.Type).includes(typeValue)
2513
- ? typeValue
2514
- : exports.Type.TYPE_UNSPECIFIED;
2515
- }
2516
- else if (supportedJsonSchemaFields.has(fieldName)) {
2517
- filteredSchema[fieldName] = fieldValue;
2518
- }
2519
- }
2520
- return filteredSchema;
2521
- }
2522
2394
  // Transforms a source input into a BatchJobSource object with validation.
2523
2395
  function tBatchJobSource(apiClient, src) {
2524
2396
  if (typeof src !== 'string' && !Array.isArray(src)) {
@@ -12854,7 +12726,7 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
12854
12726
  const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
12855
12727
  const USER_AGENT_HEADER = 'User-Agent';
12856
12728
  const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
12857
- const SDK_VERSION = '1.8.0'; // x-release-please-version
12729
+ const SDK_VERSION = '1.9.0'; // x-release-please-version
12858
12730
  const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
12859
12731
  const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
12860
12732
  const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
@@ -13085,7 +12957,14 @@ class ApiClient {
13085
12957
  const abortController = new AbortController();
13086
12958
  const signal = abortController.signal;
13087
12959
  if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {
13088
- setTimeout(() => abortController.abort(), httpOptions.timeout);
12960
+ const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);
12961
+ if (timeoutHandle &&
12962
+ typeof timeoutHandle.unref ===
12963
+ 'function') {
12964
+ // call unref to prevent nodejs process from hanging, see
12965
+ // https://nodejs.org/api/timers.html#timeoutunref
12966
+ timeoutHandle.unref();
12967
+ }
13089
12968
  }
13090
12969
  if (abortSignal) {
13091
12970
  abortSignal.addEventListener('abort', () => {
@@ -13148,7 +13027,7 @@ class ApiClient {
13148
13027
  }
13149
13028
  break;
13150
13029
  }
13151
- const chunkString = decoder.decode(value);
13030
+ const chunkString = decoder.decode(value, { stream: true });
13152
13031
  // Parse and throw an error if the chunk contains an error.
13153
13032
  try {
13154
13033
  const chunkJson = JSON.parse(chunkString);
@@ -13905,7 +13784,7 @@ class Live {
13905
13784
  if (GOOGLE_GENAI_USE_VERTEXAI) {
13906
13785
  model = 'gemini-2.0-flash-live-preview-04-09';
13907
13786
  } else {
13908
- model = 'gemini-2.0-flash-live-001';
13787
+ model = 'gemini-live-2.5-flash-preview';
13909
13788
  }
13910
13789
  const session = await ai.live.connect({
13911
13790
  model: model,
@@ -13951,6 +13830,9 @@ class Live {
13951
13830
  let keyName = 'key';
13952
13831
  if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) {
13953
13832
  console.warn('Warning: Ephemeral token support is experimental and may change in future versions.');
13833
+ if (apiVersion !== 'v1alpha') {
13834
+ console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.");
13835
+ }
13954
13836
  method = 'BidiGenerateContentConstrained';
13955
13837
  keyName = 'access_token';
13956
13838
  }
@@ -14226,7 +14108,7 @@ class Session {
14226
14108
  if (GOOGLE_GENAI_USE_VERTEXAI) {
14227
14109
  model = 'gemini-2.0-flash-live-preview-04-09';
14228
14110
  } else {
14229
- model = 'gemini-2.0-flash-live-001';
14111
+ model = 'gemini-live-2.5-flash-preview';
14230
14112
  }
14231
14113
  const session = await ai.live.connect({
14232
14114
  model: model,
@@ -14355,6 +14237,7 @@ class Models extends BaseModule {
14355
14237
  this.generateContent = async (params) => {
14356
14238
  var _a, _b, _c, _d, _e;
14357
14239
  const transformedParams = await this.processParamsForMcpUsage(params);
14240
+ this.maybeMoveToResponseJsonSchem(params);
14358
14241
  if (!hasMcpClientTools(params) || shouldDisableAfc(params.config)) {
14359
14242
  return await this.generateContentInternal(transformedParams);
14360
14243
  }
@@ -14441,6 +14324,7 @@ class Models extends BaseModule {
14441
14324
  * ```
14442
14325
  */
14443
14326
  this.generateContentStream = async (params) => {
14327
+ this.maybeMoveToResponseJsonSchem(params);
14444
14328
  if (shouldDisableAfc(params.config)) {
14445
14329
  const transformedParams = await this.processParamsForMcpUsage(params);
14446
14330
  return await this.generateContentStreamInternal(transformedParams);
@@ -14592,6 +14476,24 @@ class Models extends BaseModule {
14592
14476
  return await this.upscaleImageInternal(apiParams);
14593
14477
  };
14594
14478
  }
14479
+ /**
14480
+ * This logic is needed for GenerateContentConfig only.
14481
+ * Previously we made GenerateContentConfig.responseSchema field to accept
14482
+ * unknown. Since v1.9.0, we switch to use backend JSON schema support.
14483
+ * To maintain backward compatibility, we move the data that was treated as
14484
+ * JSON schema from the responseSchema field to the responseJsonSchema field.
14485
+ */
14486
+ maybeMoveToResponseJsonSchem(params) {
14487
+ if (params.config && params.config.responseSchema) {
14488
+ if (!params.config.responseJsonSchema) {
14489
+ if (Object.keys(params.config.responseSchema).includes('$schema')) {
14490
+ params.config.responseJsonSchema = params.config.responseSchema;
14491
+ delete params.config.responseSchema;
14492
+ }
14493
+ }
14494
+ }
14495
+ return;
14496
+ }
14595
14497
  /**
14596
14498
  * Transforms the CallableTools in the parameters to be simply Tools, it
14597
14499
  * copies the params into a new object and replaces the tools, it does not
@@ -16652,14 +16554,20 @@ class Tokens extends BaseModule {
16652
16554
  * @experimental
16653
16555
  *
16654
16556
  * @remarks
16655
- * Ephermeral auth tokens is only supported in the Gemini Developer API.
16557
+ * Ephemeral auth tokens is only supported in the Gemini Developer API.
16656
16558
  * It can be used for the session connection to the Live constrained API.
16559
+ * Support in v1alpha only.
16657
16560
  *
16658
16561
  * @param params - The parameters for the create request.
16659
16562
  * @return The created auth token.
16660
16563
  *
16661
16564
  * @example
16662
16565
  * ```ts
16566
+ * const ai = new GoogleGenAI({
16567
+ * apiKey: token.name,
16568
+ * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.
16569
+ * });
16570
+ *
16663
16571
  * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig
16664
16572
  * // when using the token in Live API sessions. Each session connection can
16665
16573
  * // use a different configuration.