← 文件首頁

原文:Get started with Gemini Enterprise Agent Platform|最後更新:2026-11-20

本快速入門說明如何安裝您所選語言的 Google Gen AI SDK,然後發出您的第一個 API 請求。

選擇驗證方法

您可以使用應用程式預設憑證 (ADC) 或 API 金鑰,向 Gemini Enterprise Agent Platform 進行驗證。建議使用 ADC。 ADC(建議) API 金鑰

事前準備

如果您尚未擁有 API 金鑰,您必須先取得一組才能繼續。如果您已有 API 金鑰,請跳至下一步。

若要建立 API 金鑰,請前往 Google Cloud 主控台中 Gemini Enterprise Agent Platform 的開始使用頁面:

前往 Gemini Enterprise Agent Platform 使用設定指令碼來設定 ADC,或手動完成這些步驟。

macOS/Linux

bash <(curl -sSL \
https://storage.googleapis.com/cloud-samples-data/adc/setup_adc.sh)

Windows

powershell -c "iex (irm https://storage.googleapis.com/cloud-samples-data/adc/setup_adc.ps1)"

主控台手動步驟

如果您已設定 ADC,請跳至下一步。

若要設定 ADC,請執行以下操作:

設定您的專案

選取專案、啟用計費、啟用 Agent Platform API,並安裝 gcloud CLI:

建立本機驗證憑證

如果您使用本機殼層,請為您的使用者帳戶建立本機驗證憑證:

gcloud auth application-default login

如果您使用 Cloud Shell,就不必執行此操作。

如果傳回驗證錯誤,且您使用外部身分提供者 (IdP),請確認您已使用同盟身分登入 gcloud CLI。

設定必要角色

如果您使用標準 API 金鑰或 ADC,您的專案也必須被授予適當的 Gemini Enterprise Agent Platform 身分與存取管理權限。如果您使用快速模式 API 金鑰,可以跳至下一步。

若要取得使用 Gemini Enterprise Agent Platform 所需的權限,請要求您的管理員在您的專案上授予您 Agent Platform User(roles/aiplatform.user)IAM 角色。

如需授予角色的更多資訊,請參閱管理專案、資料夾與組織的存取權。

您也可以透過自訂角色或其他預先定義的角色取得所需權限。

安裝 SDK 並設定您的環境

在您的本機電腦上,按一下以下其中一個分頁標籤,安裝您程式語言對應的 SDK。

Python

執行此指令,安裝並更新 Python 版 Google Gen AI SDK。

pip install --upgrade google-genai

設定環境變數:

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

Go

執行此指令,安裝並更新 Go 版 Google Gen AI SDK。

go get google.golang.org/genai

設定環境變數:

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

Node.js

執行此指令,安裝並更新 Node.js 版 Google Gen AI SDK。

npm install @google/genai

設定環境變數:

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

Java

執行此指令,安裝並更新 Java 版 Google Gen AI SDK。

Maven

將以下內容加入您的 pom.xml:

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

設定環境變數:

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

REST

設定環境變數:

GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT_ID
GOOGLE_CLOUD_LOCATION="global"
API_ENDPOINT="https://aiplatform.googleapis.com"
MODEL_ID="gemini-2.5-flash"
GENERATE_CONTENT_API="generateContent"

將 GOOGLE_CLOUD_PROJECT_ID 替換為您的 Google Cloud 專案 ID。

發出您的第一個請求

使用 generateContent 方法,向 Gemini API 傳送請求。

以下範例說明如何使用其中一種 SDK 或 REST 發出請求。若要執行 SDK 範例,請將程式碼複製到檔案(例如 request.py),並從終端機執行該檔案(例如 python request.py)。

Python

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-3.8-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:
# ...

Go

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

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateContent(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await client.models.generateContent({
    model: 'gemini-3-flash-preview',
    contents: 'How does AI work?',
  });

  console.log(response.text);

  return response.text;
}

Java

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

public class TextGenerationWithText {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates text with text input
  public static String generateContent(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      GenerateContentResponse response =
          client.models.generateContent(modelId, "How does AI work?", null);

      System.out.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:
      // ...
      return response.text();
    }
  }
}

C

using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Threading.Tasks;

public class TextGenWithTxt
{
    public async Task<string> GenerateContent(
        string projectId = "your-project-id",
        string location = "global",
        string model = "gemini-2.5-flash")
    {
        await using var client = new Client(
            project: projectId,
            location: location,
            vertexAI: true,
            httpOptions: new HttpOptions { ApiVersion = "v1" });

        GenerateContentResponse response = await client.Models.GenerateContentAsync(model: model, contents: "How does AI work?");

        string responseText = response.Candidates[0].Content.Parts[0].Text;
        Console.WriteLine(responseText);
        // Example response:
        // AI, or Artificial Intelligence, at its core, is about creating machines that can perform...
        // Here's a breakdown of how it generally works...
        return responseText;
    }
}

REST

若要傳送此提示詞請求,請從指令列執行 curl 指令,或在您的應用程式中加入此 REST 呼叫。

curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"${API_ENDPOINT}/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/${GOOGLE_CLOUD_LOCATION}/publishers/google/models/${MODEL_ID}:${GENERATE_CONTENT_API}" -d \
$'{
  "contents": {
    "role": "user",
    "parts": {
      "text": "Explain how AI works in a few words"
    }
  }
}'

模型會傳回回應。請注意,回應會分段產生,每一段都會個別進行安全性評估。


[!NOTE] 當您使用區域 API 端點(例如 us-central1)時,端點網址中的區域決定請求的處理位置。資源路徑中任何衝突的位置都會被忽略。

產生圖片

Gemini 能以對話方式產生與處理圖片。您可以使用文字、圖片,或兩者組合來提示 Gemini,完成各種與圖片相關的工作,例如圖片產生與編輯。以下程式碼示範如何根據描述性提示詞產生圖片:

您必須在設定中包含 responseModalities: ["TEXT", "IMAGE"]。這些模型不支援僅圖片輸出。

Python

import os
from io import BytesIO

from google import genai
from google.genai.types import GenerateContentConfig, Modality
from PIL import Image

client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.1-flash-image",
    contents=("Generate an image of the Eiffel tower with fireworks in the background."),
    config=GenerateContentConfig(
        response_modalities=[Modality.TEXT, Modality.IMAGE],
    ),
)
for part in response.candidates[0].content.parts:
    if part.text:
        print(part.text)
    elif part.inline_data:
        image = Image.open(BytesIO((part.inline_data.data)))
        # Ensure the output directory exists
        output_dir = "output_folder"
        os.makedirs(output_dir, exist_ok=True)
        image.save(os.path.join(output_dir, "example-image-eiffel-tower.png"))

Go

import (
    "context"
    "fmt"
    "io"
    "os"

    "google.golang.org/genai"
)

// generateMMFlashWithText demonstrates how to generate both text and image outputs.
func generateMMFlashWithText(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)
    }

    modelName := "gemini-2.5-flash-image"
    contents := []*genai.Content{
        {
            Parts: []*genai.Part{
                {Text: "Generate an image of the Eiffel tower with fireworks in the background."},
            },
            Role: genai.RoleUser,
        },
    }

    resp, err := client.Models.GenerateContent(ctx,
        modelName,
        contents,
        &genai.GenerateContentConfig{
            ResponseModalities: []string{
                string(genai.ModalityText),
                string(genai.ModalityImage),
            },
            CandidateCount: int32(1),
            SafetySettings: []*genai.SafetySetting{
                {Method: genai.HarmBlockMethodProbability},
                {Category: genai.HarmCategoryDangerousContent},
                {Threshold: genai.HarmBlockThresholdBlockMediumAndAbove},
            },
        },
    )
    if err != nil {
        return fmt.Errorf("failed to generate content: %w", err)
    }

    if len(resp.Candidates) == 0 || resp.Candidates[0].Content == nil {
        return fmt.Errorf("no candidates returned")
    }
    var fileName string
    for _, part := range resp.Candidates[0].Content.Parts {
        if part.Text != "" {
            fmt.Fprintln(w, part.Text)
        } else if part.InlineData != nil {
            fileName = "example-image-eiffel-tower.png"
            if err := os.WriteFile(fileName, part.InlineData.Data, 0o644); err != nil {
                return fmt.Errorf("failed to save image: %w", err)
            }
        }
    }
    fmt.Fprintln(w, fileName)

    // Example response:
    // I will generate an image of the Eiffel Tower at night, with a vibrant display of
    // colorful fireworks exploding in the dark sky behind it.
    // ....
    return nil
}

Node.js

const fs = require('fs');
const {GoogleGenAI, Modality} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION =
  process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';

async function generateImage(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await client.models.generateContentStream({
    model: 'gemini-2.5-flash-image',
    contents:
      'Generate an image of the Eiffel tower with fireworks in the background.',
    config: {
      responseModalities: [Modality.TEXT, Modality.IMAGE],
    },
  });

  const generatedFileNames = [];
  let imageIndex = 0;

  for await (const chunk of response) {
    const text = chunk.text;
    const data = chunk.data;
    if (text) {
      console.debug(text);
    } else if (data) {
      const outputDir = 'output-folder';
      if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, {recursive: true});
      }
      const fileName = `${outputDir}/generate_content_streaming_image_${imageIndex++}.png`;
      console.debug(`Writing response image to file: ${fileName}.`);
      try {
        fs.writeFileSync(fileName, data);
        generatedFileNames.push(fileName);
      } catch (error) {
        console.error(`Failed to write image file ${fileName}:`, error);
      }
    }
  }

  // Example response:
  //  I will generate an image of the Eiffel Tower at night, with a vibrant display of
  //  colorful fireworks exploding in the dark sky behind it. The tower will be
  //  illuminated, standing tall as the focal point of the scene, with the bursts of
  //  light from the fireworks creating a festive atmosphere.

  return generatedFileNames;
}

Java

import com.google.genai.Client;
import com.google.genai.types.Blob;
import com.google.genai.types.Candidate;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import com.google.genai.types.SafetySetting;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class ImageGenMmFlashWithText {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash-image";
    String outputFile = "resources/output/example-image-eiffel-tower.png";
    generateContent(modelId, outputFile);
  }

  // Generates an image with text input
  public static void generateContent(String modelId, String outputFile) throws IOException {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client = Client.builder().location("global").vertexAI(true).build()) {

      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .responseModalities("TEXT", "IMAGE")
              .candidateCount(1)
              .safetySettings(
                  SafetySetting.builder()
                      .method("PROBABILITY")
                      .category("HARM_CATEGORY_DANGEROUS_CONTENT")
                      .threshold("BLOCK_MEDIUM_AND_ABOVE")
                      .build())
              .build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              "Generate an image of the Eiffel tower with fireworks in the background.",
              contentConfig);

      // Get parts of the response
      List<Part> parts =
          response
              .candidates()
              .flatMap(candidates -> candidates.stream().findFirst())
              .flatMap(Candidate::content)
              .flatMap(Content::parts)
              .orElse(new ArrayList<>());

      // For each part print text if present, otherwise read image data if present and
      // write it to the output file
      for (Part part : parts) {
        if (part.text().isPresent()) {
          System.out.println(part.text().get());
        } else if (part.inlineData().flatMap(Blob::data).isPresent()) {
          BufferedImage image =
              ImageIO.read(new ByteArrayInputStream(part.inlineData().flatMap(Blob::data).get()));
          ImageIO.write(image, "png", new File(outputFile));
        }
      }

      System.out.println("Content written to: " + outputFile);
      // Example response:
      // Here is the Eiffel Tower with fireworks in the background...
      //
      // Content written to: resources/output/example-image-eiffel-tower.png
    }
  }
}

REST

若要傳送此提示詞請求,請從指令列執行 curl 指令,或在您的應用程式中加入此 REST 呼叫。

curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"${API_ENDPOINT}/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/${GOOGLE_CLOUD_LOCATION}/publishers/google/models/${MODEL_ID}:${GENERATE_CONTENT_API}" -d \
$'{
    "contents": {
      "role": "USER",
      "parts": [
        {
          "text": "Create a tutorial explaining how to make a peanut butter and
          jelly sandwich in three easy steps."
        }
      ]
    },
    "generationConfig": {
      "responseModalities": ["TEXT", "IMAGE"],
      "imageConfig": {
        "aspectRatio": "16:9",
      },
     },
     "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

模型會傳回回應。


理解圖片

Gemini 也能理解圖片。以下程式碼使用上一節產生的圖片,並使用不同的模型來推斷圖片的相關資訊:

Python

from google import genai
from google.genai.types import HttpOptions, Part

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=[
        "What is shown in this image?",
        Part.from_uri(
            file_uri="gs://cloud-samples-data/generative-ai/image/scones.jpg",
            mime_type="image/jpeg",
        ),
    ],
)
print(response.text)
# Example response:
# The image shows a flat lay of blueberry scones arranged on parchment paper. There are ...

Go

import (
    "context"
    "fmt"
    "io"

    genai "google.golang.org/genai"
)

// generateWithTextImage shows how to generate text using both text and image input
func generateWithTextImage(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)
    }

    modelName := "gemini-2.5-flash"
    contents := []*genai.Content{
        {Parts: []*genai.Part{
            {Text: "What is shown in this image?"},
            {FileData: &genai.FileData{
                // Image source: https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg
                FileURI:  "gs://cloud-samples-data/generative-ai/image/scones.jpg",
                MIMEType: "image/jpeg",
            }},
        },
            Role: genai.RoleUser},
    }

    resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
    if err != nil {
        return fmt.Errorf("failed to generate content: %w", err)
    }

    respText := resp.Text()

    fmt.Fprintln(w, respText)

    // Example response:
    // The image shows an overhead shot of a rustic, artistic arrangement on a surface that ...

    return nil
}

Node.js

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateContent(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const image = {
    fileData: {
      fileUri: 'gs://cloud-samples-data/generative-ai/image/scones.jpg',
      mimeType: 'image/jpeg',
    },
  };

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: [image, 'What is shown in this image?'],
  });

  console.log(response.text);

  return response.text;
}

Java

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;

public class TextGenerationWithTextAndImage {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates text with text and image input
  public static String generateContent(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              Content.fromParts(
                  Part.fromText("What is shown in this image?"),
                  Part.fromUri(
                      "gs://cloud-samples-data/generative-ai/image/scones.jpg", "image/jpeg")),
              null);

      System.out.print(response.text());
      // Example response:
      // The image shows a flat lay of blueberry scones arranged on parchment paper. There are ...
      return response.text();
    }
  }
}


使用程式碼執行

Gemini API 程式碼執行功能可讓模型產生並執行 Python 程式碼,並從結果中反覆學習,直到得出最終輸出。Gemini Enterprise Agent Platform 將程式碼執行作為工具提供,類似於函式呼叫。您可以使用此程式碼執行能力,建構受益於以程式碼為基礎的推理、且能產生文字輸出的應用程式。舉例來說:

Python

from google import genai
from google.genai.types import (
    GenerateContentConfig,
    HttpOptions,
    Tool,
    ToolCodeExecution,
)

client = genai.Client(http_options=HttpOptions(api_version="v1"))
model_id = "gemini-3.5-flash"

code_execution_tool = Tool(code_execution=ToolCodeExecution())
response = client.models.generate_content(
    model=model_id,
    contents="Calculate 20th fibonacci number. Then find the nearest palindrome to it.",
    config=GenerateContentConfig(
        tools=[code_execution_tool],
        temperature=0,
    ),
)
print("# Code:")
print(response.executable_code)
print("# Outcome:")
print(response.code_execution_result)

# Example response:
# # Code:
# def fibonacci(n):
#     if n <= 0:
#         return 0
#     elif n == 1:
#         return 1
#     else:
#         a, b = 0, 1
#         for _ in range(2, n + 1):
#             a, b = b, a + b
#         return b
#
# fib_20 = fibonacci(20)
# print(f'{fib_20=}')
#
# # Outcome:
# fib_20=6765

Go

import (
    "context"
    "fmt"
    "io"

    genai "google.golang.org/genai"
)

// generateWithCodeExec shows how to generate text using the code execution tool.
func generateWithCodeExec(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)
    }

    prompt := "Calculate 20th fibonacci number. Then find the nearest palindrome to it."
    contents := []*genai.Content{
        {Parts: []*genai.Part{
            {Text: prompt},
        },
            Role: genai.RoleUser},
    }
    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {CodeExecution: &genai.ToolCodeExecution{}},
        },
        Temperature: genai.Ptr(float32(0.0)),
    }
    modelName := "gemini-2.5-flash"

    resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
    if err != nil {
        return fmt.Errorf("failed to generate content: %w", err)
    }

    for _, p := range resp.Candidates[0].Content.Parts {
        if p.Text != "" {
            fmt.Fprintf(w, "Gemini: %s", p.Text)
        }
        if p.ExecutableCode != nil {
            fmt.Fprintf(w, "Language: %s\n%s\n", p.ExecutableCode.Language, p.ExecutableCode.Code)
        }
        if p.CodeExecutionResult != nil {
            fmt.Fprintf(w, "Outcome: %s\n%s\n", p.CodeExecutionResult.Outcome, p.CodeExecutionResult.Output)
        }
    }

    // Example response:
    // Gemini: Okay, I can do that. First, I'll calculate the 20th Fibonacci number. Then, I need ...
    //
    // Language: PYTHON
    //
    // def fibonacci(n):
    //    ...
    //
    // fib_20 = fibonacci(20)
    // print(f'{fib_20=}')
    //
    // Outcome: OUTCOME_OK
    // fib_20=6765
    //
    // Now that I have the 20th Fibonacci number (6765), I need to find the nearest palindrome. ...
    // ...

    return nil
}

Node.js

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateAndExecuteCode(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents:
      'Calculate 20th fibonacci number. Then find the nearest palindrome to it.',
    config: {
      tools: [{codeExecution: {}}],
      temperature: 0,
    },
  });

  console.debug(response.executableCode);

  // Example response:
  // Code:
  // function fibonacci(n) {
  //   if (n <= 0) {
  //     return 0;
  //   } else if (n === 1) {
  //     return 1;
  //   } else {
  //     let a = 0, b = 1;
  //     for (let i = 2; i <= n; i++) {
  //       [a, b] = [b, a + b];
  //     }
  //     return b;
  //   }
  // }
  //
  // const fib20 = fibonacci(20);
  // console.log(`fib20=${fib20}`);

  console.debug(response.codeExecutionResult);

  // Outcome:
  // fib20=6765

  return response.codeExecutionResult;
}

Java

import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Tool;
import com.google.genai.types.ToolCodeExecution;

public class ToolsCodeExecWithText {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates text using the Code Execution tool
  public static String generateContent(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // Create a GenerateContentConfig and set codeExecution tool
      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .tools(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build())
              .temperature(0.0F)
              .build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              "Calculate 20th fibonacci number. Then find the nearest palindrome to it.",
              contentConfig);

      System.out.println("Code: \n" + response.executableCode());
      System.out.println("Outcome: \n" + response.codeExecutionResult());
      // Example response
      // Code:
      // def fibonacci(n):
      //    if n <= 0:
      //        return 0
      //    elif n == 1:
      //        return 1
      //    else:
      //        a, b = 1, 1
      //        for _ in range(2, n):
      //            a, b = b, a + b
      //        return b
      //
      // fib_20 = fibonacci(20)
      // print(f'{fib_20=}')
      //
      // Outcome:
      // fib_20=6765
      return response.executableCode();
    }
  }
}


如需更多程式碼執行範例,請參閱程式碼執行文件。

後續步驟

現在您已發出第一個 API 請求,您可以進一步探索以下指南,瞭解如何為正式環境程式碼設定更進階的 Gemini Enterprise Agent Platform 功能: 快速入門

連結至 Knowledge MCP 伺服器

瞭解如何將您的 AI 工具連結至 Developer Knowledge MCP 伺服器,以加速開發。

快速入門

使用 ADK 進行 Vibe Code 建構代理程式

使用 Agent Development Kit (ADK) 建構、測試並部署原型代理程式至 Google Cloud 執行階段。

指南

Google Gen AI 程式庫

下載並安裝 Gemini API 的最新程式庫。

指南

使用 OpenAI 程式庫存取 Gemini 模型

瞭解如何使用 OpenAI 程式庫,在 Agent Platform 中實作並呼叫 Gemini 模型。

指南

開始使用 Gemini 3

瞭解 Gemini 3,這是我們迄今最智慧的模型系列,建立在最先進推理的基礎之上。

總覽

探索 Google 模型

探索 Agent Platform 支援的最新 Google 模型,包括 Gemini、Veo 與 Gemma。