### Quickstart Example Source: https://googleapis.github.io/js-genai A simple example demonstrating how to get started with the SDK using an API key from Google AI Studio. ```APIDOC ## Quickstart The simplest way to get started is to use an API key from Google AI Studio: ```typescript import {GoogleGenAI} from '@google/genai'; const GEMINI_API_KEY = process.env.GEMINI_API_KEY; const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); async function main() { const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: 'Why is the sky blue?', }); console.log(response.text); } main(); ``` ``` -------------------------------- ### Quickstart: Generate Content with API Key Source: https://googleapis.github.io/js-genai A simple example to get started using an API key from Google AI Studio to generate content. Ensure your API key is stored in the GEMINI_API_KEY environment variable. ```typescript import {GoogleGenAI} from '@google/genai'; const GEMINI_API_KEY = process.env.GEMINI_API_KEY; const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); async function main() { const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: 'Why is the sky blue?', }); console.log(response.text); } main(); ``` -------------------------------- ### Quickstart: Generate Content with API Key Source: https://googleapis.github.io/js-genai/release_docs/index.html A simple example demonstrating how to initialize the SDK with an API key and generate content. This is suitable for quick testing and development. ```typescript import {GoogleGenAI} from '@google/genai'; const GEMINI_API_KEY = process.env.GEMINI_API_KEY; const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); async function main() { const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: 'Why is the sky blue?', }); console.log(response.text); } main(); Copy ``` -------------------------------- ### Install @google/genai SDK Source: https://googleapis.github.io/js-genai/release_docs/index.html Install the Google Gen AI SDK using npm. Ensure Node.js version 20 or later is installed. ```bash npm install @google/genai Copy ``` -------------------------------- ### Install @google/genai SDK Source: https://googleapis.github.io/js-genai Install the Google Gen AI SDK using npm. Ensure you have Node.js version 20 or later. ```bash npm install @google/genai ``` -------------------------------- ### gRPC Service Example with google.protobuf.Empty Source: https://googleapis.github.io/js-genai/release_docs/interfaces/interactions_client.GeminiNextGenAPIClient.Webhooks.WebhookDeleteResponse.html This example demonstrates how to use google.protobuf.Empty as both the request and response type for a gRPC service method. ```proto service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } ``` -------------------------------- ### Enum Schema Examples Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.Schema.html Examples showing how to define enum constraints for string and integer types. ```json {type:STRING, format:enum, enum:["EAST", "NORTH", "SOUTH", "WEST"]} ``` ```json {type:INTEGER, format:enum, enum:["101", "201", "301"]} ``` -------------------------------- ### ReinforcementTuningExample Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.ReinforcementTuningExample.html Defines the structure for reinforcement tuning examples on Vertex AI. ```APIDOC ## Interface ReinforcementTuningExample User-facing format for Gemini Reinforcement Tuning examples on Vertex. ### Properties * `contents` (Content[]) - Optional - Multi-turn contents that represents the Prompt. * `references` (Record) - Optional - References for the given prompt. The key is the name of the reference, and the value is the reference itself. * `systemInstruction` (Content) - Optional - Corresponds to `system_instruction` in user-facing GenerateContentRequest. ``` -------------------------------- ### ToolCall Arguments Example Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.ToolCall.html Example of the structure for the optional args property. ```json {"arg1": "value1", "arg2": "value2"} ``` -------------------------------- ### Example: FileSearch with Store Names Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.FileSearch.html Specify the required file search store names when initializing the FileSearch tool. Example: `fileSearchStores/my-file-search-store-123`. ```typescript fileSearchStoreNames: ["fileSearchStores/my-file-search-store-123"] ``` -------------------------------- ### get Source: https://googleapis.github.io/js-genai/release_docs/classes/filesearchstores.FileSearchStores.html Gets a File Search Store. ```APIDOC ## get * get(params: GetFileSearchStoreParameters): Promise Gets a File Search Store. #### Parameters * params: GetFileSearchStoreParameters The parameters for getting a File Search Store. #### Returns Promise FileSearchStore. ``` -------------------------------- ### Interface ActivityStart Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.ActivityStart.html Documentation for the ActivityStart interface, which marks the start of user activity when server-side detection is disabled. ```APIDOC ## Interface ActivityStart ### Description Marks the start of user activity. This can only be sent if automatic (i.e. server-side) activity detection is disabled. ``` -------------------------------- ### Initializing for Vertex AI API Source: https://googleapis.github.io/js-genai/release_docs/classes/client.GoogleGenAI.html Example of initializing the GoogleGenAI SDK for use with the Vertex AI API by specifying project and location details. ```APIDOC import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI({ vertexai: true, project: 'PROJECT_ID', location: 'PROJECT_LOCATION' }); ``` -------------------------------- ### get Source: https://googleapis.github.io/js-genai/release_docs/classes/tunings.Tunings.html Gets a specific TuningJob by its parameters. Note that this method is experimental. ```APIDOC ## get ### Description Gets a TuningJob. This method is experimental and may change in future versions. ### Method GET ### Endpoint /v1beta/tunings/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The resource name of the TuningJob to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```json { "name": "tunings/your-tuning-job-id" } ``` ### Response #### Success Response (200) - **TuningJob** (object) - A TuningJob object. #### Response Example ```json { "name": "tunings/your-tuning-job-id", "state": "SUCCEEDED", "createTime": "2023-10-27T10:00:00Z", "updateTime": "2023-10-27T10:05:00Z" } ``` ``` -------------------------------- ### Example Usage of google.protobuf.Empty Source: https://googleapis.github.io/js-genai/release_docs/interfaces/interactions_client.GeminiNextGenAPIClient.Agents.AgentDeleteResponse.html Illustrates how google.protobuf.Empty can be used as request and response types in service definitions. ```proto service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } ``` -------------------------------- ### Integrate MCP Server with Model Context Protocol Source: https://googleapis.github.io/js-genai Utilize the experimental Model Context Protocol (MCP) support by passing a local MCP server as a tool. This example demonstrates setting up a client, connecting to an MCP server via stdio, and sending a request to the model with MCP tools. ```javascript import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai'; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; // Create server parameters for stdio connection const serverParams = new StdioClientTransport({ command: "npx", // Executable args: ["-y", "@philschmid/weather-mcp"] // MCP Server }); const client = new Client( { name: "example-client", version: "1.0.0" } ); // Configure the client const ai = new GoogleGenAI({}); // Initialize the connection between client and server await client.connect(serverParams); // Send request to the model with MCP tools const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`, config: { tools: [mcpToTool(client)], // uses the session, will automatically call the tool using automatic function calling }, }); console.log(response.text); // Close the connection await client.close(); ``` -------------------------------- ### Example Request Path Source: https://googleapis.github.io/js-genai/release_docs/types/interactions_internal_request-options.RequestOptions.html Specifies the URL path for a request. This is a common configuration when making API calls. ```string "/v1/foo" ``` -------------------------------- ### List Files with Pagination Source: https://googleapis.github.io/js-genai/release_docs/classes/files.Files.html Lists files with optional pagination. The example demonstrates how to set the page size and iterate through the returned files. ```typescript const files = await ai.files.list({config: {'pageSize': 2}}); for await (const file of files) { console.log(file); } ``` -------------------------------- ### get Source: https://googleapis.github.io/js-genai/release_docs/classes/files.Files.html Retrieves the file information from the service. ```APIDOC ## get * get(params: GetFileParameters): Promise Retrieves the file information from the service. #### Parameters * params: GetFileParameters The parameters for the get request #### Returns Promise The Promise that resolves to the types.File object requested. #### Example ``` const config: GetFileParameters = { name: fileName, }; file = await ai.files.get(config); console.log(file.name); Copy ``` ``` -------------------------------- ### systemInstruction Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.GenerateContentConfig.html Optional. Instructions provided to the model to guide its behavior and improve performance, such as setting a concise response style. ```APIDOC ### `Optional`systemInstruction systemInstruction?: ContentUnion Instructions for the model to steer it toward better performance. For example, "Answer as concisely as possible" or "Don't use technical terms in your response". ``` -------------------------------- ### Manual Pagination Control Source: https://googleapis.github.io/js-genai/release_docs/classes/pagers.Pager.html This example demonstrates manual control over pagination. It fetches items page by page and checks for the existence of a next page before proceeding. ```javascript const pager = await ai.files.list({config: {pageSize: 10}}); let page = pager.page; while (true) { for (const file of page) { console.log(file.name); } if (!pager.hasNextPage()) { break; } page = await pager.nextPage(); } ``` -------------------------------- ### Example: FileSearch with TopK Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.FileSearch.html Set the optional topK parameter to control the number of semantic retrieval chunks to retrieve. ```typescript topK: 5 ``` -------------------------------- ### Define TuningExample Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.TuningExample.html Defines the structure for a single tuning example, including optional text input and the expected model output. Note that this interface is not supported in Vertex AI. ```typescript interface TuningExample { output?: string; textInput?: string; } ``` -------------------------------- ### Error Handling Example Source: https://googleapis.github.io/js-genai/release_docs/index.html Demonstrates how to catch and handle errors raised by the API using the `ApiError` class. ```APIDOC ## Error Handling This code snippet illustrates how to implement error handling for API calls using a try-catch block. ```javascript import {GoogleGenAI} from '@google/genai'; const GEMINI_API_KEY = process.env.GEMINI_API_KEY; const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); async function main() { await ai.models.generateContent({ model: 'non-existent-model', contents: 'Write a 100-word poem.', }).catch((e) => { console.error('error name: ', e.name); console.error('error message: ', e.message); console.error('error status: ', e.status); }); } main(); ``` ``` -------------------------------- ### Agents (Deep Research) Source: https://googleapis.github.io/js-genai Utilizes specialized agents, such as `deep-research-pro-preview-12-2025`, for complex tasks. This example demonstrates starting a research agent and polling for results. ```APIDOC ## Agents (Deep Research) Uses specialized agents for complex tasks like deep research. ```javascript function sleep(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } // 1. Start the Deep Research Agent const initialInteraction = await ai.interactions.create({ input: 'Research the history of the Google TPUs with a focus on 2025 and 2026.', agent: 'deep-research-pro-preview-12-2025', background: true, }); console.log(`Research started. Interaction ID: ${initialInteraction.id}`); // 2. Poll for results while (true) { const interaction = await ai.interactions.get(initialInteraction.id); console.log(`Status: ${interaction.status}`); if (interaction.status === 'completed') { console.debug('\nFinal Report:\n', interaction.outputs); break; } else if (['failed', 'cancelled'].includes(interaction.status)) { console.log(`Failed with status: ${interaction.status}`); break; } await sleep(10000); // Sleep for 10 seconds } ``` ``` -------------------------------- ### LiveClientSetup Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.LiveClientSetup.html The LiveClientSetup interface defines the configuration options available for a live streaming session. These options allow for customization of various aspects of the session, from model behavior to audio processing and safety settings. ```APIDOC ## Interface LiveClientSetup Message contains configuration that will apply for the duration of the streaming session. ### Properties - **avatarConfig** (AvatarConfig) - Optional - Configures the avatar model behavior. - **contextWindowCompression** (ContextWindowCompressionConfig) - Optional - Configures context window compression mechanism. If included, server will compress context window to fit into given length. - **explicitVadSignal** (boolean) - Optional - Configures the explicit VAD signal. If enabled, the client will send vad_signal to indicate the start and end of speech. This allows the server to process the audio more efficiently. - **generationConfig** (GenerationConfig) - Optional - The generation configuration for the session. Note: only a subset of fields are supported. - **inputAudioTranscription** (AudioTranscriptionConfig) - Optional - The transcription of the input aligns with the input audio language. - **model** (string) - Optional - The fully qualified name of the publisher model or tuned model endpoint to use. - **outputAudioTranscription** (AudioTranscriptionConfig) - Optional - The transcription of the output aligns with the language code specified for the output audio. - **proactivity** (ProactivityConfig) - Optional - Configures the proactivity of the model. This allows the model to respond proactively to the input and to ignore irrelevant input. - **realtimeInputConfig** (RealtimeInputConfig) - Optional - Configures the realtime input behavior in BidiGenerateContent. - **safetySettings** (SafetySetting[]) - Optional - Safety settings in the request to block unsafe content in the response. - **sessionResumption** (SessionResumptionConfig) - Optional - Configures session resumption mechanism. If included server will send SessionResumptionUpdate messages. - **systemInstruction** (ContentUnion) - Optional - The user provided system instructions for the model. Note: only text should be used in parts and content in each part will be in a separate paragraph. - **tools** (ToolListUnion) - Optional - A list of `Tools` the model may use to generate the next response. A `Tool` is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the model. ``` -------------------------------- ### get Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_resources_webhooks.BaseWebhooks.html Gets a specific Webhook. ```APIDOC ## get * get( id: string, params?: | undefined | null | GeminiNextGenAPIClient.Webhooks.WebhookGetParams, options?: RequestOptions, ): APIPromise Gets a specific Webhook. #### Parameters * id: string * params: undefined | null | GeminiNextGenAPIClient.Webhooks.WebhookGetParams = {} * `Optional`options: RequestOptions #### Returns APIPromise ``` -------------------------------- ### Initialize a client with specific resources Source: https://googleapis.github.io/js-genai/release_docs/functions/interactions_tree-shakable.createClient.html Use this to create a client instance containing only the required resource classes. Ensure resources are imported from the appropriate path. ```typescript import { Interactions } from `gemini-next-gen-api/resources/interactions`; import { createClient } from `gemini-next-gen-api/tree-shakable`; const client = createClient({ resources: [Interactions], }); ``` -------------------------------- ### withOptions Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_client.GeminiNextGenAPIClient-1.html Creates a new client instance with the same options, allowing for overrides. ```APIDOC ## withOptions ### Description Creates a new client instance re-using the same options given to the current client with optional overriding. ### Parameters * **options** (Partial) - Partial client options to override. ### Returns this - A new client instance with the specified options. ``` -------------------------------- ### get Source: https://googleapis.github.io/js-genai/release_docs/classes/caches.Caches.html Gets cached content configurations. ```APIDOC ## get * get(params: GetCachedContentParameters): Promise Gets cached content configurations. #### Parameters * params: GetCachedContentParameters The parameters for the get request. #### Returns Promise The cached content. #### Example ```javascript await ai.caches.get({name: '...'}); // The server-generated resource name. ``` ``` -------------------------------- ### get Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_client.GeminiNextGenAPIClient-1.html Sends a GET request to the specified path. ```APIDOC ## get ### Description Sends a GET request to the specified path. ### Method GET ### Parameters * **path** (string) - The path for the request. * **opts** (PromiseOrValue) - Optional. Additional request options. ### Returns APIPromise - A promise that resolves with the response. ### Type Parameters * **Rsp** - The expected response type. ``` -------------------------------- ### constructor Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_resources_webhooks.BaseWebhooks.html Initializes a new instance of the BaseWebhooks class. ```APIDOC ## constructor * new BaseWebhooks(client: BaseGeminiNextGenAPIClient): BaseWebhooks #### Parameters * client: BaseGeminiNextGenAPIClient #### Returns BaseWebhooks ``` -------------------------------- ### Live Class Constructor Source: https://googleapis.github.io/js-genai/release_docs/classes/live.Live.html Initializes the Live class with necessary API client, authentication, and WebSocket factory. ```APIDOC ## constructor Live ### Description Initializes the Live class. ### Parameters - **apiClient** (ApiClient) - The API client instance. - **auth** (Auth) - The authentication object. - **webSocketFactory** (WebSocketFactory) - The WebSocket factory instance. ### Returns Live - An instance of the Live class. ``` -------------------------------- ### Live.connect Method Source: https://googleapis.github.io/js-genai/release_docs/classes/live.Live.html Establishes a connection to a specified model with given configuration and returns a Session object. ```APIDOC ## POST /connect ### Description Establishes a connection to the specified model with the given configuration and returns a Session object representing that connection. Built-in MCP support is an experimental feature and may change in future versions. ### Method POST ### Endpoint /connect ### Parameters #### Request Body - **params** (LiveConnectParameters) - Required - The parameters for establishing a connection to the model. - **model** (string) - Required - The name of the model to connect to. - **config** (object) - Optional - Configuration for the connection. - **responseModalities** (array) - Optional - Specifies the modalities for the response (e.g., [Modality.AUDIO]). - **callbacks** (object) - Optional - Callback functions for connection events. - **onopen** (function) - Called when the connection is opened. - **onmessage** (function) - Called when a message is received. - **onerror** (function) - Called when an error occurs. - **onclose** (function) - Called when the connection is closed. ### Response #### Success Response (200) - **session** (Session) - A live session object. ### Request Example ```javascript let model; if (GOOGLE_GENAI_USE_VERTEXAI) { model = 'gemini-2.0-flash-live-preview-04-09'; } else { model = 'gemini-live-2.5-flash-preview'; } const session = await ai.live.connect({ model: model, config: { responseModalities: [Modality.AUDIO], }, callbacks: { onopen: () => { console.log('Connected to the socket.'); }, onmessage: (e) => { console.log('Received message from the server: %s\n', debug(e.data)); }, onerror: (e) => { console.log('Error occurred: %s\n', debug(e.error)); }, onclose: (e) => { console.log('Connection closed.'); }, }, }); ``` ``` -------------------------------- ### Interface: PrebuiltVoiceConfig Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.PrebuiltVoiceConfig.html Configuration for a prebuilt voice. ```APIDOC ## Interface PrebuiltVoiceConfig ### Description Configuration for a prebuilt voice. ### Properties #### voiceName - **voiceName** (string) - Optional - The name of the prebuilt voice to use. ``` -------------------------------- ### get Source: https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html Fetches information about a model by name. ```APIDOC ## get ### Description Fetches information about a model by name. ### Method GET (assumed, based on typical API patterns for retrieval) ### Endpoint `/v1beta/models/{model}` (example, actual endpoint may vary) ### Parameters #### Path Parameters - **model** (string) - Required - The name of the model to fetch information for. #### Request Body (Not applicable for GET requests) ### Request Example ```javascript const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); ``` ### Response #### Success Response (200) - **Model** - Information about the model. ``` -------------------------------- ### Sample Class Methods Source: https://googleapis.github.io/js-genai/release_docs/classes/cross_sentencepiece_sentencepiece_model.pb.sentencepiece.SelfTestData.Sample.html Methods for creating, serializing, and verifying Sample objects. ```APIDOC ## Class: Sample ### Description Represents a Sample object with input and expected fields. ### Properties - **expected** (string) - Sample expected value. - **input** (string) - Sample input value. ### Methods - **constructor(properties?: ISample)**: Constructs a new Sample instance. - **toJSON()**: Converts the Sample instance to a JSON object. - **static create(properties?: ISample)**: Creates a new Sample instance. - **static decode(reader: Uint8Array | Reader, length?: number)**: Decodes a Sample message. - **static decodeDelimited(reader: Uint8Array | Reader)**: Decodes a length-delimited Sample message. - **static encode(message: ISample, writer?: Writer)**: Encodes a Sample message. - **static encodeDelimited(message: ISample, writer?: Writer)**: Encodes a length-delimited Sample message. - **static fromObject(object: { [k: string]: any })**: Creates a Sample message from a plain object. - **static getTypeUrl(typeUrlPrefix?: string)**: Gets the default type URL. - **static toObject(message: Sample, options?: IConversionOptions)**: Creates a plain object from a Sample message. - **static verify(message: { [k: string]: any })**: Verifies a Sample message; returns null if valid, or an error string. ``` -------------------------------- ### get Method Source: https://googleapis.github.io/js-genai/release_docs/classes/operations.Operations.html Retrieves the status of a long-running operation. ```APIDOC ## GET /operations/{operationId} ### Description Gets the status of a long-running operation. ### Method GET ### Endpoint /operations/{operationId} ### Parameters #### Path Parameters * **operationId** (string) - Required - The ID of the operation to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **T** (any) - The type of the operation's result. - **U** (Operation) - The type of the operation, extending Operation. #### Response Example ```json { "name": "operations/12345", "metadata": {}, "done": false, "error": null, "response": null } ``` ``` -------------------------------- ### createClient Function Source: https://googleapis.github.io/js-genai/release_docs/functions/interactions_tree-shakable.createClient.html Creates a client with a subset of the available resources to reduce bundle size. Import the resource classes you need from `gemini-next-gen-api/resources/*`. Use the BaseResource variants if you do not need to use subresources. ```APIDOC ## Function createClient ### Description Creates a client with a subset of the available resources to reduce bundle size. Import the resource classes you need from `gemini-next-gen-api/resources/*`. Use the BaseResource variants if you do not need to use subresources. ### Type Parameters * `const T extends readonly typeof APIResource[]` ### Parameters * `options`: `ClientOptions & { resources: T }` ### Returns `PartialGeminiNextGenAPIClient>` ### Example ```javascript import { Interactions } from `gemini-next-gen-api/resources/interactions`; import { createClient } from `gemini-next-gen-api/tree-shakable`; const client = createClient({ resources: [Interactions], }); ``` ``` -------------------------------- ### get Agent Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_resources_agents.BaseAgents.html Retrieves a specific Agent by its ID. ```APIDOC ## get * get( id: string, params?: undefined | null | GeminiNextGenAPIClient.Agents.AgentGetParams, options?: RequestOptions, ): APIPromise Gets a specific Agent. #### Parameters * id: string * params: undefined | null | GeminiNextGenAPIClient.Agents.AgentGetParams = {} * `Optional`options: RequestOptions #### Returns APIPromise ``` -------------------------------- ### LiveMusicClientSetup Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.LiveMusicClientSetup.html The LiveMusicClientSetup interface defines the structure for messages sent when connecting to the API. It includes an optional model property. ```APIDOC ## Interface LiveMusicClientSetup Message to be sent by the system when connecting to the API. ### Properties #### `model` (string) - Optional The model's resource name. Format: `models/{model}`. ``` -------------------------------- ### GET /documents/list Source: https://googleapis.github.io/js-genai/release_docs/classes/documents.Documents.html Lists documents available in the store. ```APIDOC ## GET /documents/list ### Description Lists documents. ### Parameters #### Query Parameters - **params** (ListDocumentsParameters) - Required - The parameters for the list request. ### Response #### Success Response (200) - **Pager** - A pager of documents. ### Request Example const documents = await ai.documents.list({parent:'rag_store_name', config: {'pageSize': 2}}); ``` -------------------------------- ### RequestInit Source: https://googleapis.github.io/js-genai/release_docs/modules/interactions_internal_builtin-types.html Represents the options that can be passed to the fetch function. ```APIDOC ## RequestInit ### Description Represents the options that can be passed to the fetch function. ### Type Definition ```typescript interface RequestInit { body?: BodyInit | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; integrity?: string; keepalive?: boolean; method?: string; mode?: RequestMode; redirect?: RequestRedirect; referrer?: string; referrerPolicy?: ReferrerPolicy; signal?: AbortSignal | null; window?: any; } ``` ``` -------------------------------- ### GET /documents Source: https://googleapis.github.io/js-genai/release_docs/classes/documents.Documents.html Retrieves details of a specific document. ```APIDOC ## GET /documents ### Description Gets a Document. ### Parameters #### Query Parameters - **params** (GetDocumentParameters) - Required - The parameters for getting a document. ### Response #### Success Response (200) - **Document** - The requested document object. ``` -------------------------------- ### WebhookGetParams Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/interactions_client.GeminiNextGenAPIClient.Webhooks.WebhookGetParams.html Defines the parameters for the Webhook GET request. ```APIDOC ## Interface WebhookGetParams ### Description Defines the parameters for the Webhook GET request. ### Properties #### Query Parameters - **api_version** (string) - Optional - Which version of the API to use. ``` -------------------------------- ### Define LiveClientSetup Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.LiveClientSetup.html The interface structure for configuring a streaming session. ```typescript interface LiveClientSetup { avatarConfig?: AvatarConfig; contextWindowCompression?: ContextWindowCompressionConfig; explicitVadSignal?: boolean; generationConfig?: GenerationConfig; inputAudioTranscription?: AudioTranscriptionConfig; model?: string; outputAudioTranscription?: AudioTranscriptionConfig; proactivity?: ProactivityConfig; realtimeInputConfig?: RealtimeInputConfig; safetySettings?: SafetySetting[]; sessionResumption?: SessionResumptionConfig; systemInstruction?: ContentUnion; tools?: ToolListUnion; } ``` -------------------------------- ### Batches API - get Source: https://googleapis.github.io/js-genai/release_docs/classes/batches.Batches.html Retrieves batch job configurations. ```APIDOC ## POST /v1/batches:get ### Description Retrieves batch job configurations. ### Method POST ### Endpoint /v1/batches:get ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (GetBatchJobParameters) - Required - The parameters for the get request. - **name** (string) - Required - The server-generated resource name of the batch job to retrieve. ### Request Example ```javascript const batchJob = await ai.batches.get({name: 'projects/my-project/locations/us-central1/batches/my-batch-id'}); console.log(batchJob); ``` ### Response #### Success Response (200) - **BatchJob** (object) - The batch job configuration. - **name** (string) - The resource name of the batch job. - **state** (string) - The current state of the batch job. - **model** (string) - The model used for the batch job. - **createTime** (string) - The timestamp when the batch job was created. - **updateTime** (string) - The timestamp when the batch job was last updated. - **error** (object) - Details about any errors encountered. #### Response Example ```json { "name": "projects/my-project/locations/us-central1/batches/my-batch-id", "state": "SUCCEEDED", "model": "gemini-2.0-flash", "createTime": "2023-10-27T10:00:00Z", "updateTime": "2023-10-27T10:05:00Z" } ``` ``` -------------------------------- ### Interface: SpeakerVoiceConfig Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.SpeakerVoiceConfig.html Configuration for a single speaker in a multi-speaker setup. ```APIDOC ## Interface SpeakerVoiceConfig Configuration for a single speaker in a multi-speaker setup. ### Properties - **speaker** (string) - Optional - The name of the speaker. This should be the same as the speaker name used in the prompt. - **voiceConfig** (VoiceConfig) - Optional - The configuration for the voice of this speaker. ``` -------------------------------- ### create Source: https://googleapis.github.io/js-genai/release_docs/classes/filesearchstores.FileSearchStores.html Creates a File Search Store. ```APIDOC ## create * create(params: CreateFileSearchStoreParameters): Promise Creates a File Search Store. #### Parameters * params: CreateFileSearchStoreParameters The parameters for creating a File Search Store. #### Returns Promise FileSearchStore. ``` -------------------------------- ### Get Library Version Source: https://googleapis.github.io/js-genai/release_docs/variables/interactions_version.VERSION.html Access the current version of the @google/genai library. ```APIDOC ## Get Library Version ### Description Retrieves the current version of the @google/genai JavaScript library. ### Method GET ### Endpoint /interactions/version ### Parameters None ### Request Example None ### Response #### Success Response (200) - **version** (string) - The current version string of the library. #### Response Example { "version": "0.0.1" } ``` -------------------------------- ### OperationGetParameters Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.OperationGetParameters.html Defines the parameters for the get method of the operations module. ```APIDOC ## Interface OperationGetParameters ### Description Parameters for the get method of the operations module. ### Type Parameters * **T** * **U** extends Operation ### Properties #### config (optional) - **config** (GetOperationConfig) - Used to override the default configuration. #### operation - **operation** (U) - The operation to be retrieved. ``` -------------------------------- ### Model Context Protocol (MCP) Support Source: https://googleapis.github.io/js-genai/release_docs/index.html Demonstrates how to use the experimental Model Context Protocol (MCP) support by passing a local MCP server as a tool. ```APIDOC ## Model Context Protocol (MCP) Support (Experimental) ### Description Built-in MCP support is an experimental feature. You can pass a local MCP server as a tool directly. ### Method `POST` ### Endpoint `/v1beta/models/{model}:generateContent` ### Parameters #### Request Body ```json { "model": "gemini-2.5-flash", "contents": "What is the weather in London in [current date]?", "config": { "tools": [ // MCP tool configuration would go here, e.g., using mcpToTool(client) ] } } ``` ### Example Usage ```javascript import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai'; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; // Create server parameters for stdio connection const serverParams = new StdioClientTransport({ command: "npx", // Executable args: ["-y", "@philschmid/weather-mcp"] // MCP Server }); const client = new Client( { name: "example-client", version: "1.0.0" } ); // Configure the client const ai = new GoogleGenAI({}); // Initialize the connection between client and server await client.connect(serverParams); // Send request to the model with MCP tools const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`, config: { tools: [mcpToTool(client)], // uses the session, will automatically call the tool using automatic function calling }, }); console.log(response.text); // Close the connection await client.close(); ``` ``` -------------------------------- ### GetTuningJobParameters Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.GetTuningJobParameters.html Defines the parameters for the get method related to tuning jobs. ```APIDOC ## Interface GetTuningJobParameters Parameters for the get method. ### Properties - **config** (GetTuningJobConfig) - Optional - Optional parameters for the request. - **name** (string) - Required - The name of the tuning job. ``` -------------------------------- ### get Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_client.GeminiNextGenAPIClient.Webhooks-1.html Retrieves a specific Webhook by its ID, with optional parameters and request options. ```APIDOC ## get * get( id: string, params?: | undefined | null | GeminiNextGenAPIClient.Webhooks.WebhookGetParams, options?: RequestOptions, ): APIPromise Gets a specific Webhook. #### Parameters * id: string * params: undefined | null | GeminiNextGenAPIClient.Webhooks.WebhookGetParams = {} * `Optional`options: RequestOptions #### Returns APIPromise ``` -------------------------------- ### Define SpeakerVoiceConfig Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.SpeakerVoiceConfig.html Interface definition for configuring a speaker in a multi-speaker setup. ```typescript interface SpeakerVoiceConfig { speaker?: string; voiceConfig?: VoiceConfig; } ``` -------------------------------- ### Initialize gcloud CLI for Authentication Source: https://googleapis.github.io/js-genai Use this command to create local authentication credentials for your user account when using the Gemini Enterprise Agent Platform. ```bash gcloud auth application-default login ``` -------------------------------- ### Initialize gcloud CLI for Authentication Source: https://googleapis.github.io/js-genai/release_docs/index.html Use this command to create local authentication credentials for your user account when using the Gemini Enterprise Agent Platform. ```bash gcloud auth application-default login Copy ``` -------------------------------- ### Define OperationGetParameters Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.OperationGetParameters.html Interface definition for the get method parameters in the operations module. ```typescript interface OperationGetParameters> { config?: GetOperationConfig; operation: U; } ``` ```typescript config?: GetOperationConfig ``` ```typescript operation: U ``` -------------------------------- ### GET /response/text Source: https://googleapis.github.io/js-genai/release_docs/classes/types.GenerateContentResponse.html Retrieves the concatenated text content from the first candidate of a model response. ```APIDOC ## GET /response/text ### Description Returns the concatenation of all text parts from the first candidate in the response. If non-text parts exist, they are ignored, and a warning is logged. ### Returns - **string | undefined** - The concatenated text content. ### Remarks If multiple candidates exist, only the first is processed. Thought parts are excluded from the returned text. ``` -------------------------------- ### GET /interactions/{id} Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_client.GeminiNextGenAPIClient.Interactions-1.html Retrieves the full details of a single interaction based on its ID. ```APIDOC ## GET /interactions/{id} ### Description Retrieves the full details of a single interaction based on its Interaction.id. Supports both standard and streaming responses. ### Method GET ### Endpoint /interactions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the interaction. ### Response #### Success Response (200) - **Interaction** (object) - The interaction details or a stream of SSE events. ### Response Example { "api_version": "api_version" } ``` -------------------------------- ### Interface RagChunkPageSpan Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.RagChunkPageSpan.html Defines the structure for specifying the start and end pages of a document chunk. ```APIDOC ## Interface RagChunkPageSpan ### Description Represents where the chunk starts and ends in the document. This data type is not supported in Gemini API. ### Properties - **firstPage** (number) - Optional - Page where chunk starts in the document. Inclusive. 1-indexed. - **lastPage** (number) - Optional - Page where chunk ends in the document. Inclusive. 1-indexed. ``` -------------------------------- ### NodeJS Environment Variables Initialization Source: https://googleapis.github.io/js-genai Initialize the SDK in NodeJS environments using environment variables. ```APIDOC ### (Optional) (NodeJS only) Using environment variables: For NodeJS environments, you can create a client by configuring the necessary environment variables. Configuration setup instructions depends on whether you're using the Gemini Developer API or the Gemini Enterprise Agent Platform. **Gemini Developer API:** Set `GOOGLE_API_KEY` as shown below: ```bash export GOOGLE_API_KEY='your-api-key' ``` **Gemini Enterprise Agent Platform:** Set `GOOGLE_GENAI_USE_ENTERPRISE`, `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, as shown below: ```bash export GOOGLE_GENAI_USE_ENTERPRISE=true export GOOGLE_CLOUD_PROJECT='your-project-id' export GOOGLE_CLOUD_LOCATION='us-central1' ``` ```typescript import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI(); ``` ``` -------------------------------- ### Define startIndex Property Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.Citation.html Represents the start index of the citation in the content. This is an output-only property. ```typescript startIndex?: number ``` -------------------------------- ### create Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_resources_webhooks.BaseWebhooks.html Creates a new Webhook. ```APIDOC ## create * create( params: GeminiNextGenAPIClient.Webhooks.WebhookCreateParams, options?: RequestOptions, ): APIPromise Creates a new Webhook. #### Parameters * params: GeminiNextGenAPIClient.Webhooks.WebhookCreateParams * `Optional`options: RequestOptions #### Returns APIPromise ``` -------------------------------- ### Define GetTuningJobParameters Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.GetTuningJobParameters.html Represents the required parameters for the get method in tuning job operations. ```typescript interface GetTuningJobParameters { config?: GetTuningJobConfig; name: string; } ``` -------------------------------- ### GetOperationParameters Interface Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.GetOperationParameters.html Defines the parameters available for the GET method, allowing customization of operation configurations. ```APIDOC ## Interface GetOperationParameters ### Description Parameters for the GET method. ### Properties - **config** (GetOperationConfig) - Optional - Used to override the default configuration. - **operationName** (string) - Required - The server-assigned name for the operation. ``` -------------------------------- ### Gemini Developer API Initialization Source: https://googleapis.github.io/js-genai Initialize the SDK for the Gemini Developer API using an API key. ```APIDOC ## Initialization ### Gemini Developer API For server-side applications, initialize using an API key, which can be acquired from Google AI Studio: ```typescript import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); ``` #### Browser Caution **API Key Security:** Avoid exposing API keys in client-side code. Use server-side implementations in production environments. In the browser the initialization code is identical: ```typescript import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); ``` ``` -------------------------------- ### Gemini Enterprise Agent Platform Initialization Source: https://googleapis.github.io/js-genai Initialize the SDK for the Gemini Enterprise Agent Platform. ```APIDOC ### Gemini Enterprise Agent Platform Sample code for Gemini Enterprise Agent Platform initialization: ```typescript import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({ enterprise: true, project: 'your_project', location: 'your_location', }); ``` ``` -------------------------------- ### GET /interactions (Non-Streaming) Source: https://googleapis.github.io/js-genai/release_docs/interfaces/interactions_client.GeminiNextGenAPIClient.Interactions.InteractionGetParamsNonStreaming.html Retrieves interaction data without streaming, using the InteractionGetParamsNonStreaming interface. ```APIDOC ## GET /interactions ### Description Retrieves interaction data from the Gemini Next Gen API client in a non-streaming format. ### Method GET ### Endpoint /interactions ### Parameters #### Path Parameters - **api_version** (string) - Optional - Which version of the API to use. #### Query Parameters - **include_input** (boolean) - Optional - If set to true, includes the input in the response. - **last_event_id** (string) - Optional - If set, resumes the interaction stream from the next chunk after the event marked by the event id. Can only be used if `stream` is true. - **stream** (boolean) - Optional - If set to true, the generated content will be streamed incrementally. Set to false for non-streaming. ``` -------------------------------- ### GET /interactions/{id} Source: https://googleapis.github.io/js-genai/release_docs/classes/interactions_resources_interactions.BaseInteractions.html Retrieves the full details of a single interaction by its ID, with support for streaming. ```APIDOC ## GET /interactions/{id} ### Description Retrieves the full details of a single interaction based on its ID. Supports both standard and streaming responses. ### Method GET ### Endpoint /interactions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the interaction. ### Response #### Success Response (200) - **Interaction** (object) - The interaction details or a stream of SSE events. ### Response Example { "api_version": "api_version" } ``` -------------------------------- ### Initialize Gemini Enterprise Agent Platform Source: https://googleapis.github.io/js-genai Sample code for initializing the Google Gen AI SDK for the Gemini Enterprise Agent Platform, requiring project and location details. ```typescript import { GoogleGenAI } from '@google/genai'; const ai = new GoogleGenAI({ enterprise: true, project: 'your_project', location: 'your_location', }); ``` -------------------------------- ### Optional baseModel Property Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.CreateTuningJobParametersPrivate.html Specify the base model for tuning, for example, 'gemini-2.5-flash'. This is an optional field. ```typescript baseModel?: string ``` -------------------------------- ### CreateTuningJobConfig Source: https://googleapis.github.io/js-genai/release_docs/interfaces/types.CreateTuningJobConfig.html The CreateTuningJobConfig interface defines the optional parameters for creating a fine-tuning job. It includes settings for model adaptation, training parameters, and output configuration. ```APIDOC ## Interface CreateTuningJobConfig Fine-tuning job creation request - optional fields. ### Properties abortSignal? adapterSize? baseTeacherModel? batchSize? beta? checkpointInterval? compositeRewardConfig? customBaseModel? description? encryptionSpec? epochCount? evaluateInterval? exportLastCheckpointOnly? httpOptions? labels? learningRate? learningRateMultiplier? maxOutputTokens? method? outputUri? preTunedModelCheckpointId? rewardConfig? samplesPerPrompt? sftLossWeightMultiplier? thinkingLevel? tunedModelDisplayName? tunedTeacherModelSource? tuningMode? validationDataset? validationDatasetUri? ### `Optional`abortSignal abortSignal?: AbortSignal Abort signal which can be used to cancel the request. NOTE: AbortSignal is a client-only operation. Using it to cancel an operation will not cancel the request in the service. You will still be charged usage for any applicable operations. ### `Optional`adapterSize adapterSize?: AdapterSize Adapter size for tuning. ### `Optional`baseTeacherModel baseTeacherModel?: string The base teacher model that is being distilled. Distillation only. ### `Optional`batchSize batchSize?: number The batch size hyperparameter for tuning. This is only supported for OSS models in Gemini Enterprise Agent Platform. ### `Optional`beta beta?: number Weight for KL Divergence regularization, Preference Optimization tuning only. ### `Optional`checkpointInterval checkpointInterval?: number How often at steps to save checkpoints during training. Reinforcement tuning only. ### `Optional`compositeRewardConfig compositeRewardConfig?: CompositeReinforcementTuningRewardConfig Composite reward function configuration for reinforcement tuning. Reinforcement tuning only. ### `Optional`customBaseModel customBaseModel?: string Custom base model for tuning. This is only supported for OSS models in Gemini Enterprise Agent Platform. ### `Optional`description description?: string The description of the TuningJob ### `Optional`encryptionSpec encryptionSpec?: EncryptionSpec The encryption spec of the tuning job. Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with provided encryption key. ### `Optional`epochCount epochCount?: number Number of complete passes the model makes over the entire training dataset during training. ### `Optional`evaluateInterval evaluateInterval?: number How often at steps to evaluate the tuning job during training. Reinforcement tuning only. ### `Optional`exportLastCheckpointOnly exportLastCheckpointOnly?: boolean If set to true, disable intermediate checkpoints and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints. ### `Optional`httpOptions httpOptions?: HttpOptions Used to override HTTP request options. ### `Optional`labels labels?: Record Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. ### `Optional`learningRate learningRate?: number The learning rate for tuning. OSS models only. Mutually exclusive with learning_rate_multiplier. ### `Optional`learningRateMultiplier learningRateMultiplier?: number Multiplier for adjusting the default learning rate. 1P models only. Mutually exclusive with learning_rate. ### `Optional`maxOutputTokens maxOutputTokens?: number The maximum number of tokens to generate per prompt. Reinforcement tuning only. ``` -------------------------------- ### Initialize SDK using Environment Variables (NodeJS) Source: https://googleapis.github.io/js-genai/release_docs/index.html Initialize the Google Gen AI SDK in a NodeJS environment after configuring the necessary environment variables for either the Gemini Developer API or the Enterprise Agent Platform. ```typescript import {GoogleGenAI} from '@google/genai'; const ai = new GoogleGenAI(); Copy ```