@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.
@@ -3510,11 +3510,38 @@ export { Image_2 as Image }
3510
3510
 
3511
3511
  /** Enum that specifies the language of the text in the prompt. */
3512
3512
  export declare enum ImagePromptLanguage {
3513
+ /**
3514
+ * Auto-detect the language.
3515
+ */
3513
3516
  auto = "auto",
3517
+ /**
3518
+ * English
3519
+ */
3514
3520
  en = "en",
3521
+ /**
3522
+ * Japanese
3523
+ */
3515
3524
  ja = "ja",
3525
+ /**
3526
+ * Korean
3527
+ */
3516
3528
  ko = "ko",
3517
- hi = "hi"
3529
+ /**
3530
+ * Hindi
3531
+ */
3532
+ hi = "hi",
3533
+ /**
3534
+ * Chinese
3535
+ */
3536
+ zh = "zh",
3537
+ /**
3538
+ * Portuguese
3539
+ */
3540
+ pt = "pt",
3541
+ /**
3542
+ * Spanish
3543
+ */
3544
+ es = "es"
3518
3545
  }
3519
3546
 
3520
3547
  /** Config for inlined request. */
@@ -3812,7 +3839,7 @@ export declare class Live {
3812
3839
  if (GOOGLE_GENAI_USE_VERTEXAI) {
3813
3840
  model = 'gemini-2.0-flash-live-preview-04-09';
3814
3841
  } else {
3815
- model = 'gemini-2.0-flash-live-001';
3842
+ model = 'gemini-live-2.5-flash-preview';
3816
3843
  }
3817
3844
  const session = await ai.live.connect({
3818
3845
  model: model,
@@ -4778,6 +4805,14 @@ export declare class Models extends BaseModule {
4778
4805
  * ```
4779
4806
  */
4780
4807
  generateContent: (params: types.GenerateContentParameters) => Promise<types.GenerateContentResponse>;
4808
+ /**
4809
+ * This logic is needed for GenerateContentConfig only.
4810
+ * Previously we made GenerateContentConfig.responseSchema field to accept
4811
+ * unknown. Since v1.9.0, we switch to use backend JSON schema support.
4812
+ * To maintain backward compatibility, we move the data that was treated as
4813
+ * JSON schema from the responseSchema field to the responseJsonSchema field.
4814
+ */
4815
+ private maybeMoveToResponseJsonSchem;
4781
4816
  /**
4782
4817
  * Makes an API request to generate content with a given model and yields the
4783
4818
  * response in chunks.
@@ -5790,7 +5825,7 @@ export declare class Session {
5790
5825
  if (GOOGLE_GENAI_USE_VERTEXAI) {
5791
5826
  model = 'gemini-2.0-flash-live-preview-04-09';
5792
5827
  } else {
5793
- model = 'gemini-2.0-flash-live-001';
5828
+ model = 'gemini-live-2.5-flash-preview';
5794
5829
  }
5795
5830
  const session = await ai.live.connect({
5796
5831
  model: model,
@@ -6085,14 +6120,20 @@ export declare class Tokens extends BaseModule {
6085
6120
  * @experimental
6086
6121
  *
6087
6122
  * @remarks
6088
- * Ephermeral auth tokens is only supported in the Gemini Developer API.
6123
+ * Ephemeral auth tokens is only supported in the Gemini Developer API.
6089
6124
  * It can be used for the session connection to the Live constrained API.
6125
+ * Support in v1alpha only.
6090
6126
  *
6091
6127
  * @param params - The parameters for the create request.
6092
6128
  * @return The created auth token.
6093
6129
  *
6094
6130
  * @example
6095
6131
  * ```ts
6132
+ * const ai = new GoogleGenAI({
6133
+ * apiKey: token.name,
6134
+ * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.
6135
+ * });
6136
+ *
6096
6137
  * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig
6097
6138
  * // when using the token in Live API sessions. Each session connection can
6098
6139
  * // use a different configuration.
@@ -1,5 +1,3 @@
1
- import { z } from 'zod';
2
-
3
1
  /**
4
2
  * @license
5
3
  * Copyright 2025 Google LLC
@@ -791,11 +789,38 @@ var PersonGeneration;
791
789
  /** Enum that specifies the language of the text in the prompt. */
792
790
  var ImagePromptLanguage;
793
791
  (function (ImagePromptLanguage) {
792
+ /**
793
+ * Auto-detect the language.
794
+ */
794
795
  ImagePromptLanguage["auto"] = "auto";
796
+ /**
797
+ * English
798
+ */
795
799
  ImagePromptLanguage["en"] = "en";
800
+ /**
801
+ * Japanese
802
+ */
796
803
  ImagePromptLanguage["ja"] = "ja";
804
+ /**
805
+ * Korean
806
+ */
797
807
  ImagePromptLanguage["ko"] = "ko";
808
+ /**
809
+ * Hindi
810
+ */
798
811
  ImagePromptLanguage["hi"] = "hi";
812
+ /**
813
+ * Chinese
814
+ */
815
+ ImagePromptLanguage["zh"] = "zh";
816
+ /**
817
+ * Portuguese
818
+ */
819
+ ImagePromptLanguage["pt"] = "pt";
820
+ /**
821
+ * Spanish
822
+ */
823
+ ImagePromptLanguage["es"] = "es";
799
824
  })(ImagePromptLanguage || (ImagePromptLanguage = {}));
800
825
  /** Enum representing the mask mode of a mask reference image. */
801
826
  var MaskReferenceMode;
@@ -1896,133 +1921,12 @@ function tContents(origin) {
1896
1921
  }
1897
1922
  return result;
1898
1923
  }
1899
- // The fields that are supported by JSONSchema. Must be kept in sync with the
1900
- // JSONSchema interface above.
1901
- const supportedJsonSchemaFields = new Set([
1902
- 'type',
1903
- 'format',
1904
- 'title',
1905
- 'description',
1906
- 'default',
1907
- 'items',
1908
- 'minItems',
1909
- 'maxItems',
1910
- 'enum',
1911
- 'properties',
1912
- 'required',
1913
- 'minProperties',
1914
- 'maxProperties',
1915
- 'minimum',
1916
- 'maximum',
1917
- 'minLength',
1918
- 'maxLength',
1919
- 'pattern',
1920
- 'anyOf',
1921
- 'propertyOrdering',
1922
- ]);
1923
- const jsonSchemaTypeValidator = z.enum([
1924
- 'string',
1925
- 'number',
1926
- 'integer',
1927
- 'object',
1928
- 'array',
1929
- 'boolean',
1930
- 'null',
1931
- ]);
1932
- // Handles all types and arrays of all types.
1933
- const schemaTypeUnion = z.union([
1934
- jsonSchemaTypeValidator,
1935
- z.array(jsonSchemaTypeValidator),
1936
- ]);
1937
- /**
1938
- * Creates a zod validator for JSONSchema.
1939
- *
1940
- * @param strictMode Whether to enable strict mode, default to true. When
1941
- * strict mode is enabled, the zod validator will throw error if there
1942
- * are unrecognized fields in the input data. If strict mode is
1943
- * disabled, the zod validator will ignore the unrecognized fields, only
1944
- * populate the fields that are listed in the JSONSchema. Regardless of
1945
- * the mode the type mismatch will always result in an error, for example
1946
- * items field should be a single JSONSchema, but for tuple type it would
1947
- * be an array of JSONSchema, this will always result in an error.
1948
- * @return The zod validator for JSONSchema.
1949
- */
1950
- function createJsonSchemaValidator(strictMode = true) {
1951
- const jsonSchemaValidator = z.lazy(() => {
1952
- // Define the base object shape *inside* the z.lazy callback
1953
- const baseShape = z.object({
1954
- // --- Type ---
1955
- type: schemaTypeUnion.optional(),
1956
- // --- Annotations ---
1957
- format: z.string().optional(),
1958
- title: z.string().optional(),
1959
- description: z.string().optional(),
1960
- default: z.unknown().optional(),
1961
- // --- Array Validations ---
1962
- items: jsonSchemaValidator.optional(),
1963
- minItems: z.coerce.string().optional(),
1964
- maxItems: z.coerce.string().optional(),
1965
- // --- Generic Validations ---
1966
- enum: z.array(z.unknown()).optional(),
1967
- // --- Object Validations ---
1968
- properties: z.record(z.string(), jsonSchemaValidator).optional(),
1969
- required: z.array(z.string()).optional(),
1970
- minProperties: z.coerce.string().optional(),
1971
- maxProperties: z.coerce.string().optional(),
1972
- propertyOrdering: z.array(z.string()).optional(),
1973
- // --- Numeric Validations ---
1974
- minimum: z.number().optional(),
1975
- maximum: z.number().optional(),
1976
- // --- String Validations ---
1977
- minLength: z.coerce.string().optional(),
1978
- maxLength: z.coerce.string().optional(),
1979
- pattern: z.string().optional(),
1980
- // --- Schema Composition ---
1981
- anyOf: z.array(jsonSchemaValidator).optional(),
1982
- // --- Additional Properties --- This field is not included in the
1983
- // JSONSchema, will not be communicated to the model, it is here purely
1984
- // for enabling the zod validation strict mode.
1985
- additionalProperties: z.boolean().optional(),
1986
- });
1987
- // Conditionally apply .strict() based on the flag
1988
- return strictMode ? baseShape.strict() : baseShape;
1989
- });
1990
- return jsonSchemaValidator;
1991
- }
1992
1924
  /*
1993
- Handle type field:
1994
- The resulted type field in JSONSchema form zod_to_json_schema can be either
1995
- an array consist of primitive types or a single primitive type.
1996
- This is due to the optimization of zod_to_json_schema, when the types in the
1997
- union are primitive types without any additional specifications,
1998
- zod_to_json_schema will squash the types into an array instead of put them
1999
- in anyOf fields. Otherwise, it will put the types in anyOf fields.
2000
- See the following link for more details:
2001
- https://github.com/zodjs/zod-to-json-schema/blob/main/src/index.ts#L101
2002
- The logic here is trying to undo that optimization, flattening the array of
2003
- types to anyOf fields.
2004
- type field
2005
- |
2006
- ___________________________
2007
- / \
2008
- / \
2009
- / \
2010
- Array Type.*
2011
- / \ |
2012
- Include null. Not included null type = Type.*.
2013
- [null, Type.*, Type.*] multiple types.
2014
- [null, Type.*] [Type.*, Type.*]
2015
- / \
2016
- remove null \
2017
- add nullable = true \
2018
- / \ \
2019
- [Type.*] [Type.*, Type.*] \
2020
- only one type left multiple types left \
2021
- add type = Type.*. \ /
2022
- \ /
2023
- not populate the type field in final result
2024
- and make the types into anyOf fields
2025
- anyOf:[{type: 'Type.*'}, {type: 'Type.*'}];
1925
+ Transform the type field from an array of types to an array of anyOf fields.
1926
+ Example:
1927
+ {type: ['STRING', 'NUMBER']}
1928
+ will be transformed to
1929
+ {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}
2026
1930
  */
2027
1931
  function flattenTypeArrayToAnyOf(typeList, resultingSchema) {
2028
1932
  if (typeList.includes('null')) {
@@ -2168,15 +2072,11 @@ function processJsonSchema(_jsonSchema) {
2168
2072
  // https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7
2169
2073
  // typebox can return unknown, see details in
2170
2074
  // https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35
2075
+ // Note: proper json schemas with the $schema field set never arrive to this
2076
+ // transformer. Schemas with $schema are routed to the equivalent API json
2077
+ // schema field.
2171
2078
  function tSchema(schema) {
2172
- if (Object.keys(schema).includes('$schema')) {
2173
- delete schema['$schema'];
2174
- const validatedJsonSchema = createJsonSchemaValidator().parse(schema);
2175
- return processJsonSchema(validatedJsonSchema);
2176
- }
2177
- else {
2178
- return processJsonSchema(schema);
2179
- }
2079
+ return processJsonSchema(schema);
2180
2080
  }
2181
2081
  function tSpeechConfig(speechConfig) {
2182
2082
  if (typeof speechConfig === 'object') {
@@ -2205,10 +2105,28 @@ function tTool(tool) {
2205
2105
  if (tool.functionDeclarations) {
2206
2106
  for (const functionDeclaration of tool.functionDeclarations) {
2207
2107
  if (functionDeclaration.parameters) {
2208
- functionDeclaration.parameters = tSchema(functionDeclaration.parameters);
2108
+ if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {
2109
+ functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters);
2110
+ }
2111
+ else {
2112
+ if (!functionDeclaration.parametersJsonSchema) {
2113
+ functionDeclaration.parametersJsonSchema =
2114
+ functionDeclaration.parameters;
2115
+ delete functionDeclaration.parameters;
2116
+ }
2117
+ }
2209
2118
  }
2210
2119
  if (functionDeclaration.response) {
2211
- functionDeclaration.response = tSchema(functionDeclaration.response);
2120
+ if (!Object.keys(functionDeclaration.response).includes('$schema')) {
2121
+ functionDeclaration.response = processJsonSchema(functionDeclaration.response);
2122
+ }
2123
+ else {
2124
+ if (!functionDeclaration.responseJsonSchema) {
2125
+ functionDeclaration.responseJsonSchema =
2126
+ functionDeclaration.response;
2127
+ delete functionDeclaration.response;
2128
+ }
2129
+ }
2212
2130
  }
2213
2131
  }
2214
2132
  }
@@ -2413,7 +2331,7 @@ function mcpToGeminiTool(mcpTool, config = {}) {
2413
2331
  const functionDeclaration = {
2414
2332
  name: mcpToolSchema['name'],
2415
2333
  description: mcpToolSchema['description'],
2416
- parameters: processJsonSchema(filterToJsonSchema(mcpToolSchema['inputSchema'])),
2334
+ parametersJsonSchema: mcpToolSchema['inputSchema'],
2417
2335
  };
2418
2336
  if (config.behavior) {
2419
2337
  functionDeclaration['behavior'] = config.behavior;
@@ -2445,53 +2363,6 @@ function mcpToolsToGeminiTool(mcpTools, config = {}) {
2445
2363
  }
2446
2364
  return { functionDeclarations: functionDeclarations };
2447
2365
  }
2448
- // Filters the list schema field to only include fields that are supported by
2449
- // JSONSchema.
2450
- function filterListSchemaField(fieldValue) {
2451
- const listSchemaFieldValue = [];
2452
- for (const listFieldValue of fieldValue) {
2453
- listSchemaFieldValue.push(filterToJsonSchema(listFieldValue));
2454
- }
2455
- return listSchemaFieldValue;
2456
- }
2457
- // Filters the dict schema field to only include fields that are supported by
2458
- // JSONSchema.
2459
- function filterDictSchemaField(fieldValue) {
2460
- const dictSchemaFieldValue = {};
2461
- for (const [key, value] of Object.entries(fieldValue)) {
2462
- const valueRecord = value;
2463
- dictSchemaFieldValue[key] = filterToJsonSchema(valueRecord);
2464
- }
2465
- return dictSchemaFieldValue;
2466
- }
2467
- // Filters the schema to only include fields that are supported by JSONSchema.
2468
- function filterToJsonSchema(schema) {
2469
- const schemaFieldNames = new Set(['items']); // 'additional_properties' to come
2470
- const listSchemaFieldNames = new Set(['anyOf']); // 'one_of', 'all_of', 'not' to come
2471
- const dictSchemaFieldNames = new Set(['properties']); // 'defs' to come
2472
- const filteredSchema = {};
2473
- for (const [fieldName, fieldValue] of Object.entries(schema)) {
2474
- if (schemaFieldNames.has(fieldName)) {
2475
- filteredSchema[fieldName] = filterToJsonSchema(fieldValue);
2476
- }
2477
- else if (listSchemaFieldNames.has(fieldName)) {
2478
- filteredSchema[fieldName] = filterListSchemaField(fieldValue);
2479
- }
2480
- else if (dictSchemaFieldNames.has(fieldName)) {
2481
- filteredSchema[fieldName] = filterDictSchemaField(fieldValue);
2482
- }
2483
- else if (fieldName === 'type') {
2484
- const typeValue = fieldValue.toUpperCase();
2485
- filteredSchema[fieldName] = Object.values(Type).includes(typeValue)
2486
- ? typeValue
2487
- : Type.TYPE_UNSPECIFIED;
2488
- }
2489
- else if (supportedJsonSchemaFields.has(fieldName)) {
2490
- filteredSchema[fieldName] = fieldValue;
2491
- }
2492
- }
2493
- return filteredSchema;
2494
- }
2495
2366
  // Transforms a source input into a BatchJobSource object with validation.
2496
2367
  function tBatchJobSource(apiClient, src) {
2497
2368
  if (typeof src !== 'string' && !Array.isArray(src)) {
@@ -12827,7 +12698,7 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
12827
12698
  const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
12828
12699
  const USER_AGENT_HEADER = 'User-Agent';
12829
12700
  const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
12830
- const SDK_VERSION = '1.8.0'; // x-release-please-version
12701
+ const SDK_VERSION = '1.9.0'; // x-release-please-version
12831
12702
  const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
12832
12703
  const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
12833
12704
  const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
@@ -13058,7 +12929,14 @@ class ApiClient {
13058
12929
  const abortController = new AbortController();
13059
12930
  const signal = abortController.signal;
13060
12931
  if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {
13061
- setTimeout(() => abortController.abort(), httpOptions.timeout);
12932
+ const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);
12933
+ if (timeoutHandle &&
12934
+ typeof timeoutHandle.unref ===
12935
+ 'function') {
12936
+ // call unref to prevent nodejs process from hanging, see
12937
+ // https://nodejs.org/api/timers.html#timeoutunref
12938
+ timeoutHandle.unref();
12939
+ }
13062
12940
  }
13063
12941
  if (abortSignal) {
13064
12942
  abortSignal.addEventListener('abort', () => {
@@ -13121,7 +12999,7 @@ class ApiClient {
13121
12999
  }
13122
13000
  break;
13123
13001
  }
13124
- const chunkString = decoder.decode(value);
13002
+ const chunkString = decoder.decode(value, { stream: true });
13125
13003
  // Parse and throw an error if the chunk contains an error.
13126
13004
  try {
13127
13005
  const chunkJson = JSON.parse(chunkString);
@@ -13878,7 +13756,7 @@ class Live {
13878
13756
  if (GOOGLE_GENAI_USE_VERTEXAI) {
13879
13757
  model = 'gemini-2.0-flash-live-preview-04-09';
13880
13758
  } else {
13881
- model = 'gemini-2.0-flash-live-001';
13759
+ model = 'gemini-live-2.5-flash-preview';
13882
13760
  }
13883
13761
  const session = await ai.live.connect({
13884
13762
  model: model,
@@ -13924,6 +13802,9 @@ class Live {
13924
13802
  let keyName = 'key';
13925
13803
  if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) {
13926
13804
  console.warn('Warning: Ephemeral token support is experimental and may change in future versions.');
13805
+ if (apiVersion !== 'v1alpha') {
13806
+ 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.");
13807
+ }
13927
13808
  method = 'BidiGenerateContentConstrained';
13928
13809
  keyName = 'access_token';
13929
13810
  }
@@ -14199,7 +14080,7 @@ class Session {
14199
14080
  if (GOOGLE_GENAI_USE_VERTEXAI) {
14200
14081
  model = 'gemini-2.0-flash-live-preview-04-09';
14201
14082
  } else {
14202
- model = 'gemini-2.0-flash-live-001';
14083
+ model = 'gemini-live-2.5-flash-preview';
14203
14084
  }
14204
14085
  const session = await ai.live.connect({
14205
14086
  model: model,
@@ -14328,6 +14209,7 @@ class Models extends BaseModule {
14328
14209
  this.generateContent = async (params) => {
14329
14210
  var _a, _b, _c, _d, _e;
14330
14211
  const transformedParams = await this.processParamsForMcpUsage(params);
14212
+ this.maybeMoveToResponseJsonSchem(params);
14331
14213
  if (!hasMcpClientTools(params) || shouldDisableAfc(params.config)) {
14332
14214
  return await this.generateContentInternal(transformedParams);
14333
14215
  }
@@ -14414,6 +14296,7 @@ class Models extends BaseModule {
14414
14296
  * ```
14415
14297
  */
14416
14298
  this.generateContentStream = async (params) => {
14299
+ this.maybeMoveToResponseJsonSchem(params);
14417
14300
  if (shouldDisableAfc(params.config)) {
14418
14301
  const transformedParams = await this.processParamsForMcpUsage(params);
14419
14302
  return await this.generateContentStreamInternal(transformedParams);
@@ -14565,6 +14448,24 @@ class Models extends BaseModule {
14565
14448
  return await this.upscaleImageInternal(apiParams);
14566
14449
  };
14567
14450
  }
14451
+ /**
14452
+ * This logic is needed for GenerateContentConfig only.
14453
+ * Previously we made GenerateContentConfig.responseSchema field to accept
14454
+ * unknown. Since v1.9.0, we switch to use backend JSON schema support.
14455
+ * To maintain backward compatibility, we move the data that was treated as
14456
+ * JSON schema from the responseSchema field to the responseJsonSchema field.
14457
+ */
14458
+ maybeMoveToResponseJsonSchem(params) {
14459
+ if (params.config && params.config.responseSchema) {
14460
+ if (!params.config.responseJsonSchema) {
14461
+ if (Object.keys(params.config.responseSchema).includes('$schema')) {
14462
+ params.config.responseJsonSchema = params.config.responseSchema;
14463
+ delete params.config.responseSchema;
14464
+ }
14465
+ }
14466
+ }
14467
+ return;
14468
+ }
14568
14469
  /**
14569
14470
  * Transforms the CallableTools in the parameters to be simply Tools, it
14570
14471
  * copies the params into a new object and replaces the tools, it does not
@@ -16625,14 +16526,20 @@ class Tokens extends BaseModule {
16625
16526
  * @experimental
16626
16527
  *
16627
16528
  * @remarks
16628
- * Ephermeral auth tokens is only supported in the Gemini Developer API.
16529
+ * Ephemeral auth tokens is only supported in the Gemini Developer API.
16629
16530
  * It can be used for the session connection to the Live constrained API.
16531
+ * Support in v1alpha only.
16630
16532
  *
16631
16533
  * @param params - The parameters for the create request.
16632
16534
  * @return The created auth token.
16633
16535
  *
16634
16536
  * @example
16635
16537
  * ```ts
16538
+ * const ai = new GoogleGenAI({
16539
+ * apiKey: token.name,
16540
+ * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.
16541
+ * });
16542
+ *
16636
16543
  * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig
16637
16544
  * // when using the token in Live API sessions. Each session connection can
16638
16545
  * // use a different configuration.