Google Gen AI SDK

本指南說明如何開始使用 Google Gen AI SDK,涵蓋下列主題:

  • Python 快速入門:安裝 SDK,並執行完整 Vertex AI 平台或 Vertex AI 快速模式的快速入門導覽課程。
  • Go 快速入門導覽課程:安裝 SDK 並執行 Go 快速入門導覽課程。
  • Node.js 快速入門導覽課程:安裝 SDK 並執行 Node.js 快速入門導覽課程。
  • Java 快速入門:安裝 SDK 並執行 Java 快速入門導覽課程。

Google Gen AI SDK 提供統一的介面,方便您透過 Gemini Developer API 和 Vertex AI 上的 Gemini API,使用 Gemini 2.5 Pro 和 Gemini 2.0 模型。除了少數例外情況,在一個平台上執行的程式碼也能在兩個平台上執行。也就是說,您可以使用 Gemini 開發人員 API 製作應用程式原型,然後將應用程式遷移至 Vertex AI,不必重寫程式碼。

如要進一步瞭解 Gemini 開發人員 API 與 Vertex AI 上的 Gemini 之間的差異,請參閱「從 Gemini 開發人員 API 遷移至 Vertex AI 中的 Gemini API」。

Python

Google Gen AI SDK for Python 可在 PyPI 和 GitHub 上取得:

詳情請參閱 Python SDK 參考資料

安裝

pip install --upgrade google-genai

設定環境變數,透過 Vertex AI 使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

快速入門導覽課程

Google Gen AI SDK for Python 可搭配完整版 Vertex AI 平台或 Vertex AI 快速模式使用。下表摘要說明主要差異。

選項 說明 驗證 用途
Vertex AI 可存取所有 Google Cloud 功能和服務,包括企業級安全防護、管理和 MLOps 功能。 使用標準 Google Cloud 驗證 (例如 應用程式預設憑證)。 需要與其他 Google Cloud 服務整合的正式版應用程式、企業環境和工作流程。
Vertex AI (快速模式) 簡化 API 金鑰的使用體驗,方便您快速製作原型和開發,與 Gemini Developer API 類似。 使用 API 金鑰進行驗證。 快速製作原型、查看教學課程,以及快速上手,無須完成完整的 Google Cloud 專案設定。詳情請參閱 [Vertex AI 快速模式](/vertex-ai/generative-ai/docs/start/express-mode/overview#workflow)。


選擇符合您用途的分頁。

Vertex AI

本範例使用標準 Google Cloud 驗證,連線至 Vertex AI API。

from google import genai
from google.genai.types import HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="How does AI work?",
)
print(response.text)
# Example response:
# Okay, let's break down how AI works. It's a broad field, so I'll focus on the ...
#
# Here's a simplified overview:
# ...

Vertex AI (Express 模式)

這個範例會使用 API 金鑰,以快捷模式連線至 Vertex AI API。

from google import genai

# TODO(developer): Update below line
API_KEY = "YOUR_API_KEY"

client = genai.Client(vertexai=True, api_key=API_KEY)

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Explain bubble sort to me.",
)

print(response.text)
# Example response:
# Bubble Sort is a simple sorting algorithm that repeatedly steps through the list

Go

Go 適用的 Google Gen AI SDK 已在 go.dev 和 GitHub 上架:

安裝

go get google.golang.org/genai

設定環境變數,透過 Vertex AI 使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

快速入門導覽課程

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/genai"
)

// generateWithText shows how to generate text using a text prompt.
func generateWithText(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	resp, err := client.Models.GenerateContent(ctx,
		"gemini-2.5-flash",
		genai.Text("How does AI work?"),
		nil,
	)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)
	// Example response:
	// That's a great question! Understanding how AI works can feel like ...
	// ...
	// **1. The Foundation: Data and Algorithms**
	// ...

	return nil
}

Node.js

TypeScript 和 JavaScript 適用的 Google Gen AI SDK 可在 npm 和 GitHub 上取得:

安裝

npm install @google/genai

設定環境變數,透過 Vertex AI 使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

快速入門導覽課程

/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import {GoogleGenAI} from '@google/genai';

const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION;
const GOOGLE_GENAI_USE_VERTEXAI = process.env.GOOGLE_GENAI_USE_VERTEXAI;

async function generateContentFromMLDev() {
  const ai = new GoogleGenAI({vertexai: false, apiKey: GEMINI_API_KEY});
  const response = await ai.models.generateContent({
    model: 'gemini-2.0-flash',
    contents: 'why is the sky blue?',
  });
  console.debug(response.text);
}

async function generateContentFromVertexAI() {
  const ai = new GoogleGenAI({
    vertexai: true,
    project: GOOGLE_CLOUD_PROJECT,
    location: GOOGLE_CLOUD_LOCATION,
  });
  const response = await ai.models.generateContent({
    model: 'gemini-2.0-flash',
    contents: 'why is the sky blue?',
  });
  console.debug(response.text);
}

async function main() {
  if (GOOGLE_GENAI_USE_VERTEXAI) {
    await generateContentFromVertexAI().catch((e) =>
      console.error('got error', e),
    );
  } else {
    await generateContentFromMLDev().catch((e) =>
      console.error('got error', e),
    );
  }
}

main();

Java

Java 適用的 Google Gen AI SDK 可在 Maven Central 和 GitHub 上取得:

Maven 安裝

<dependencies>
  <dependency>
    <groupId>com.google.genai</groupId>
    <artifactId>google-genai</artifactId>
    <version>1.4.1</version>
  </dependency>
</dependencies>

設定環境變數,透過 Vertex AI 使用 Gen AI SDK:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

快速入門導覽課程

/*
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Usage:
 *
 * <p>1a. If you are using Vertex AI, setup ADC to get credentials:
 * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp
 *
 * <p>Then set Project, Location, and USE_VERTEXAI flag as environment variables:
 *
 * <p>export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT
 *
 * <p>export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION
 *
 * <p>export GOOGLE_GENAI_USE_VERTEXAI=true
 *
 * <p>1b. If you are using Gemini Developer API, set an API key environment variable. You can find a
 * list of available API keys here: https://aistudio.google.com/app/apikey
 *
 * <p>export GOOGLE_API_KEY=YOUR_API_KEY
 *
 * <p>2. Compile the java package and run the sample code.
 *
 * <p>mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContent"
 * -Dexec.args="YOUR_MODEL_ID"
 */
package com.google.genai.examples;

import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;

/** An example of using the Unified Gen AI Java SDK to generate content. */
public final class GenerateContent {
  public static void main(String[] args) {
    String modelId = "gemini-2.0-flash-001";
    if (args.length != 0) {
      modelId = args[0];
    }

    // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API
    // key from the environment variable `GOOGLE_API_KEY`. Vertex AI API can be used by setting the
    // environment variables `GOOGLE_CLOUD_LOCATION` and `GOOGLE_CLOUD_PROJECT`, as well as setting
    // `GOOGLE_GENAI_USE_VERTEXAI` to "true".
    //
    // Note: Some services are only available in a specific API backend (Gemini or Vertex), you will
    // get a `UnsupportedOperationException` if you try to use a service that is not available in
    // the backend you are using.
    Client client = new Client();

    if (client.vertexAI()) {
      System.out.println("Using Vertex AI");
    } else {
      System.out.println("Using Gemini Developer API");
    }

    GenerateContentResponse response =
        client.models.generateContent(modelId, "What is your name?", null);

    // Gets the text string from the response by the quick accessor method `text()`.
    System.out.println("Unary response: " + response.text());

    // Gets the http headers from the response.
    response
        .sdkHttpResponse()
        .ifPresent(
            httpResponse ->
                System.out.println("Response headers: " + httpResponse.headers().orElse(null)));
  }

  private GenerateContent() {}
}