@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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,3 @@
1
- import { z } from 'zod';
2
-
3
1
  /**
4
2
  * @license
5
3
  * Copyright 2025 Google LLC
@@ -761,11 +759,38 @@ var PersonGeneration;
761
759
  /** Enum that specifies the language of the text in the prompt. */
762
760
  var ImagePromptLanguage;
763
761
  (function (ImagePromptLanguage) {
762
+ /**
763
+ * Auto-detect the language.
764
+ */
764
765
  ImagePromptLanguage["auto"] = "auto";
766
+ /**
767
+ * English
768
+ */
765
769
  ImagePromptLanguage["en"] = "en";
770
+ /**
771
+ * Japanese
772
+ */
766
773
  ImagePromptLanguage["ja"] = "ja";
774
+ /**
775
+ * Korean
776
+ */
767
777
  ImagePromptLanguage["ko"] = "ko";
778
+ /**
779
+ * Hindi
780
+ */
768
781
  ImagePromptLanguage["hi"] = "hi";
782
+ /**
783
+ * Chinese
784
+ */
785
+ ImagePromptLanguage["zh"] = "zh";
786
+ /**
787
+ * Portuguese
788
+ */
789
+ ImagePromptLanguage["pt"] = "pt";
790
+ /**
791
+ * Spanish
792
+ */
793
+ ImagePromptLanguage["es"] = "es";
769
794
  })(ImagePromptLanguage || (ImagePromptLanguage = {}));
770
795
  /** Enum representing the mask mode of a mask reference image. */
771
796
  var MaskReferenceMode;
@@ -1866,133 +1891,12 @@ function tContents(origin) {
1866
1891
  }
1867
1892
  return result;
1868
1893
  }
1869
- // The fields that are supported by JSONSchema. Must be kept in sync with the
1870
- // JSONSchema interface above.
1871
- const supportedJsonSchemaFields = new Set([
1872
- 'type',
1873
- 'format',
1874
- 'title',
1875
- 'description',
1876
- 'default',
1877
- 'items',
1878
- 'minItems',
1879
- 'maxItems',
1880
- 'enum',
1881
- 'properties',
1882
- 'required',
1883
- 'minProperties',
1884
- 'maxProperties',
1885
- 'minimum',
1886
- 'maximum',
1887
- 'minLength',
1888
- 'maxLength',
1889
- 'pattern',
1890
- 'anyOf',
1891
- 'propertyOrdering',
1892
- ]);
1893
- const jsonSchemaTypeValidator = z.enum([
1894
- 'string',
1895
- 'number',
1896
- 'integer',
1897
- 'object',
1898
- 'array',
1899
- 'boolean',
1900
- 'null',
1901
- ]);
1902
- // Handles all types and arrays of all types.
1903
- const schemaTypeUnion = z.union([
1904
- jsonSchemaTypeValidator,
1905
- z.array(jsonSchemaTypeValidator),
1906
- ]);
1907
- /**
1908
- * Creates a zod validator for JSONSchema.
1909
- *
1910
- * @param strictMode Whether to enable strict mode, default to true. When
1911
- * strict mode is enabled, the zod validator will throw error if there
1912
- * are unrecognized fields in the input data. If strict mode is
1913
- * disabled, the zod validator will ignore the unrecognized fields, only
1914
- * populate the fields that are listed in the JSONSchema. Regardless of
1915
- * the mode the type mismatch will always result in an error, for example
1916
- * items field should be a single JSONSchema, but for tuple type it would
1917
- * be an array of JSONSchema, this will always result in an error.
1918
- * @return The zod validator for JSONSchema.
1919
- */
1920
- function createJsonSchemaValidator(strictMode = true) {
1921
- const jsonSchemaValidator = z.lazy(() => {
1922
- // Define the base object shape *inside* the z.lazy callback
1923
- const baseShape = z.object({
1924
- // --- Type ---
1925
- type: schemaTypeUnion.optional(),
1926
- // --- Annotations ---
1927
- format: z.string().optional(),
1928
- title: z.string().optional(),
1929
- description: z.string().optional(),
1930
- default: z.unknown().optional(),
1931
- // --- Array Validations ---
1932
- items: jsonSchemaValidator.optional(),
1933
- minItems: z.coerce.string().optional(),
1934
- maxItems: z.coerce.string().optional(),
1935
- // --- Generic Validations ---
1936
- enum: z.array(z.unknown()).optional(),
1937
- // --- Object Validations ---
1938
- properties: z.record(z.string(), jsonSchemaValidator).optional(),
1939
- required: z.array(z.string()).optional(),
1940
- minProperties: z.coerce.string().optional(),
1941
- maxProperties: z.coerce.string().optional(),
1942
- propertyOrdering: z.array(z.string()).optional(),
1943
- // --- Numeric Validations ---
1944
- minimum: z.number().optional(),
1945
- maximum: z.number().optional(),
1946
- // --- String Validations ---
1947
- minLength: z.coerce.string().optional(),
1948
- maxLength: z.coerce.string().optional(),
1949
- pattern: z.string().optional(),
1950
- // --- Schema Composition ---
1951
- anyOf: z.array(jsonSchemaValidator).optional(),
1952
- // --- Additional Properties --- This field is not included in the
1953
- // JSONSchema, will not be communicated to the model, it is here purely
1954
- // for enabling the zod validation strict mode.
1955
- additionalProperties: z.boolean().optional(),
1956
- });
1957
- // Conditionally apply .strict() based on the flag
1958
- return strictMode ? baseShape.strict() : baseShape;
1959
- });
1960
- return jsonSchemaValidator;
1961
- }
1962
1894
  /*
1963
- Handle type field:
1964
- The resulted type field in JSONSchema form zod_to_json_schema can be either
1965
- an array consist of primitive types or a single primitive type.
1966
- This is due to the optimization of zod_to_json_schema, when the types in the
1967
- union are primitive types without any additional specifications,
1968
- zod_to_json_schema will squash the types into an array instead of put them
1969
- in anyOf fields. Otherwise, it will put the types in anyOf fields.
1970
- See the following link for more details:
1971
- https://github.com/zodjs/zod-to-json-schema/blob/main/src/index.ts#L101
1972
- The logic here is trying to undo that optimization, flattening the array of
1973
- types to anyOf fields.
1974
- type field
1975
- |
1976
- ___________________________
1977
- / \
1978
- / \
1979
- / \
1980
- Array Type.*
1981
- / \ |
1982
- Include null. Not included null type = Type.*.
1983
- [null, Type.*, Type.*] multiple types.
1984
- [null, Type.*] [Type.*, Type.*]
1985
- / \
1986
- remove null \
1987
- add nullable = true \
1988
- / \ \
1989
- [Type.*] [Type.*, Type.*] \
1990
- only one type left multiple types left \
1991
- add type = Type.*. \ /
1992
- \ /
1993
- not populate the type field in final result
1994
- and make the types into anyOf fields
1995
- anyOf:[{type: 'Type.*'}, {type: 'Type.*'}];
1895
+ Transform the type field from an array of types to an array of anyOf fields.
1896
+ Example:
1897
+ {type: ['STRING', 'NUMBER']}
1898
+ will be transformed to
1899
+ {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}
1996
1900
  */
1997
1901
  function flattenTypeArrayToAnyOf(typeList, resultingSchema) {
1998
1902
  if (typeList.includes('null')) {
@@ -2138,15 +2042,11 @@ function processJsonSchema(_jsonSchema) {
2138
2042
  // https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7
2139
2043
  // typebox can return unknown, see details in
2140
2044
  // https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35
2045
+ // Note: proper json schemas with the $schema field set never arrive to this
2046
+ // transformer. Schemas with $schema are routed to the equivalent API json
2047
+ // schema field.
2141
2048
  function tSchema(schema) {
2142
- if (Object.keys(schema).includes('$schema')) {
2143
- delete schema['$schema'];
2144
- const validatedJsonSchema = createJsonSchemaValidator().parse(schema);
2145
- return processJsonSchema(validatedJsonSchema);
2146
- }
2147
- else {
2148
- return processJsonSchema(schema);
2149
- }
2049
+ return processJsonSchema(schema);
2150
2050
  }
2151
2051
  function tSpeechConfig(speechConfig) {
2152
2052
  if (typeof speechConfig === 'object') {
@@ -2175,10 +2075,28 @@ function tTool(tool) {
2175
2075
  if (tool.functionDeclarations) {
2176
2076
  for (const functionDeclaration of tool.functionDeclarations) {
2177
2077
  if (functionDeclaration.parameters) {
2178
- functionDeclaration.parameters = tSchema(functionDeclaration.parameters);
2078
+ if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {
2079
+ functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters);
2080
+ }
2081
+ else {
2082
+ if (!functionDeclaration.parametersJsonSchema) {
2083
+ functionDeclaration.parametersJsonSchema =
2084
+ functionDeclaration.parameters;
2085
+ delete functionDeclaration.parameters;
2086
+ }
2087
+ }
2179
2088
  }
2180
2089
  if (functionDeclaration.response) {
2181
- functionDeclaration.response = tSchema(functionDeclaration.response);
2090
+ if (!Object.keys(functionDeclaration.response).includes('$schema')) {
2091
+ functionDeclaration.response = processJsonSchema(functionDeclaration.response);
2092
+ }
2093
+ else {
2094
+ if (!functionDeclaration.responseJsonSchema) {
2095
+ functionDeclaration.responseJsonSchema =
2096
+ functionDeclaration.response;
2097
+ delete functionDeclaration.response;
2098
+ }
2099
+ }
2182
2100
  }
2183
2101
  }
2184
2102
  }
@@ -2383,7 +2301,7 @@ function mcpToGeminiTool(mcpTool, config = {}) {
2383
2301
  const functionDeclaration = {
2384
2302
  name: mcpToolSchema['name'],
2385
2303
  description: mcpToolSchema['description'],
2386
- parameters: processJsonSchema(filterToJsonSchema(mcpToolSchema['inputSchema'])),
2304
+ parametersJsonSchema: mcpToolSchema['inputSchema'],
2387
2305
  };
2388
2306
  if (config.behavior) {
2389
2307
  functionDeclaration['behavior'] = config.behavior;
@@ -2415,53 +2333,6 @@ function mcpToolsToGeminiTool(mcpTools, config = {}) {
2415
2333
  }
2416
2334
  return { functionDeclarations: functionDeclarations };
2417
2335
  }
2418
- // Filters the list schema field to only include fields that are supported by
2419
- // JSONSchema.
2420
- function filterListSchemaField(fieldValue) {
2421
- const listSchemaFieldValue = [];
2422
- for (const listFieldValue of fieldValue) {
2423
- listSchemaFieldValue.push(filterToJsonSchema(listFieldValue));
2424
- }
2425
- return listSchemaFieldValue;
2426
- }
2427
- // Filters the dict schema field to only include fields that are supported by
2428
- // JSONSchema.
2429
- function filterDictSchemaField(fieldValue) {
2430
- const dictSchemaFieldValue = {};
2431
- for (const [key, value] of Object.entries(fieldValue)) {
2432
- const valueRecord = value;
2433
- dictSchemaFieldValue[key] = filterToJsonSchema(valueRecord);
2434
- }
2435
- return dictSchemaFieldValue;
2436
- }
2437
- // Filters the schema to only include fields that are supported by JSONSchema.
2438
- function filterToJsonSchema(schema) {
2439
- const schemaFieldNames = new Set(['items']); // 'additional_properties' to come
2440
- const listSchemaFieldNames = new Set(['anyOf']); // 'one_of', 'all_of', 'not' to come
2441
- const dictSchemaFieldNames = new Set(['properties']); // 'defs' to come
2442
- const filteredSchema = {};
2443
- for (const [fieldName, fieldValue] of Object.entries(schema)) {
2444
- if (schemaFieldNames.has(fieldName)) {
2445
- filteredSchema[fieldName] = filterToJsonSchema(fieldValue);
2446
- }
2447
- else if (listSchemaFieldNames.has(fieldName)) {
2448
- filteredSchema[fieldName] = filterListSchemaField(fieldValue);
2449
- }
2450
- else if (dictSchemaFieldNames.has(fieldName)) {
2451
- filteredSchema[fieldName] = filterDictSchemaField(fieldValue);
2452
- }
2453
- else if (fieldName === 'type') {
2454
- const typeValue = fieldValue.toUpperCase();
2455
- filteredSchema[fieldName] = Object.values(Type).includes(typeValue)
2456
- ? typeValue
2457
- : Type.TYPE_UNSPECIFIED;
2458
- }
2459
- else if (supportedJsonSchemaFields.has(fieldName)) {
2460
- filteredSchema[fieldName] = fieldValue;
2461
- }
2462
- }
2463
- return filteredSchema;
2464
- }
2465
2336
  // Transforms a source input into a BatchJobSource object with validation.
2466
2337
  function tBatchJobSource(apiClient, src) {
2467
2338
  if (typeof src !== 'string' && !Array.isArray(src)) {
@@ -6377,7 +6248,7 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
6377
6248
  const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
6378
6249
  const USER_AGENT_HEADER = 'User-Agent';
6379
6250
  const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
6380
- const SDK_VERSION = '1.8.0'; // x-release-please-version
6251
+ const SDK_VERSION = '1.9.0'; // x-release-please-version
6381
6252
  const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
6382
6253
  const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
6383
6254
  const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
@@ -6608,7 +6479,14 @@ class ApiClient {
6608
6479
  const abortController = new AbortController();
6609
6480
  const signal = abortController.signal;
6610
6481
  if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {
6611
- setTimeout(() => abortController.abort(), httpOptions.timeout);
6482
+ const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);
6483
+ if (timeoutHandle &&
6484
+ typeof timeoutHandle.unref ===
6485
+ 'function') {
6486
+ // call unref to prevent nodejs process from hanging, see
6487
+ // https://nodejs.org/api/timers.html#timeoutunref
6488
+ timeoutHandle.unref();
6489
+ }
6612
6490
  }
6613
6491
  if (abortSignal) {
6614
6492
  abortSignal.addEventListener('abort', () => {
@@ -6671,7 +6549,7 @@ class ApiClient {
6671
6549
  }
6672
6550
  break;
6673
6551
  }
6674
- const chunkString = decoder.decode(value);
6552
+ const chunkString = decoder.decode(value, { stream: true });
6675
6553
  // Parse and throw an error if the chunk contains an error.
6676
6554
  try {
6677
6555
  const chunkJson = JSON.parse(chunkString);
@@ -13971,7 +13849,7 @@ class Live {
13971
13849
  if (GOOGLE_GENAI_USE_VERTEXAI) {
13972
13850
  model = 'gemini-2.0-flash-live-preview-04-09';
13973
13851
  } else {
13974
- model = 'gemini-2.0-flash-live-001';
13852
+ model = 'gemini-live-2.5-flash-preview';
13975
13853
  }
13976
13854
  const session = await ai.live.connect({
13977
13855
  model: model,
@@ -14017,6 +13895,9 @@ class Live {
14017
13895
  let keyName = 'key';
14018
13896
  if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) {
14019
13897
  console.warn('Warning: Ephemeral token support is experimental and may change in future versions.');
13898
+ if (apiVersion !== 'v1alpha') {
13899
+ 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.");
13900
+ }
14020
13901
  method = 'BidiGenerateContentConstrained';
14021
13902
  keyName = 'access_token';
14022
13903
  }
@@ -14292,7 +14173,7 @@ class Session {
14292
14173
  if (GOOGLE_GENAI_USE_VERTEXAI) {
14293
14174
  model = 'gemini-2.0-flash-live-preview-04-09';
14294
14175
  } else {
14295
- model = 'gemini-2.0-flash-live-001';
14176
+ model = 'gemini-live-2.5-flash-preview';
14296
14177
  }
14297
14178
  const session = await ai.live.connect({
14298
14179
  model: model,
@@ -14421,6 +14302,7 @@ class Models extends BaseModule {
14421
14302
  this.generateContent = async (params) => {
14422
14303
  var _a, _b, _c, _d, _e;
14423
14304
  const transformedParams = await this.processParamsForMcpUsage(params);
14305
+ this.maybeMoveToResponseJsonSchem(params);
14424
14306
  if (!hasMcpClientTools(params) || shouldDisableAfc(params.config)) {
14425
14307
  return await this.generateContentInternal(transformedParams);
14426
14308
  }
@@ -14507,6 +14389,7 @@ class Models extends BaseModule {
14507
14389
  * ```
14508
14390
  */
14509
14391
  this.generateContentStream = async (params) => {
14392
+ this.maybeMoveToResponseJsonSchem(params);
14510
14393
  if (shouldDisableAfc(params.config)) {
14511
14394
  const transformedParams = await this.processParamsForMcpUsage(params);
14512
14395
  return await this.generateContentStreamInternal(transformedParams);
@@ -14658,6 +14541,24 @@ class Models extends BaseModule {
14658
14541
  return await this.upscaleImageInternal(apiParams);
14659
14542
  };
14660
14543
  }
14544
+ /**
14545
+ * This logic is needed for GenerateContentConfig only.
14546
+ * Previously we made GenerateContentConfig.responseSchema field to accept
14547
+ * unknown. Since v1.9.0, we switch to use backend JSON schema support.
14548
+ * To maintain backward compatibility, we move the data that was treated as
14549
+ * JSON schema from the responseSchema field to the responseJsonSchema field.
14550
+ */
14551
+ maybeMoveToResponseJsonSchem(params) {
14552
+ if (params.config && params.config.responseSchema) {
14553
+ if (!params.config.responseJsonSchema) {
14554
+ if (Object.keys(params.config.responseSchema).includes('$schema')) {
14555
+ params.config.responseJsonSchema = params.config.responseSchema;
14556
+ delete params.config.responseSchema;
14557
+ }
14558
+ }
14559
+ }
14560
+ return;
14561
+ }
14661
14562
  /**
14662
14563
  * Transforms the CallableTools in the parameters to be simply Tools, it
14663
14564
  * copies the params into a new object and replaces the tools, it does not
@@ -16718,14 +16619,20 @@ class Tokens extends BaseModule {
16718
16619
  * @experimental
16719
16620
  *
16720
16621
  * @remarks
16721
- * Ephermeral auth tokens is only supported in the Gemini Developer API.
16622
+ * Ephemeral auth tokens is only supported in the Gemini Developer API.
16722
16623
  * It can be used for the session connection to the Live constrained API.
16624
+ * Support in v1alpha only.
16723
16625
  *
16724
16626
  * @param params - The parameters for the create request.
16725
16627
  * @return The created auth token.
16726
16628
  *
16727
16629
  * @example
16728
16630
  * ```ts
16631
+ * const ai = new GoogleGenAI({
16632
+ * apiKey: token.name,
16633
+ * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.
16634
+ * });
16635
+ *
16729
16636
  * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig
16730
16637
  * // when using the token in Live API sessions. Each session connection can
16731
16638
  * // use a different configuration.