文字生成

本頁說明如何使用 Google Cloud 控制台、REST API 和支援的 SDK,將即時通訊提示傳送至 Gemini 模型。

如要瞭解如何將圖片和其他媒體加入要求,請參閱「圖像解讀」。

如需 Gemini 支援的語言清單,請參閱「語言支援」。


如要探索 Gemini Enterprise Agent Platform 提供的生成式 AI 模型和 API,請前往 Google Cloud 控制台中的 Model Garden。

前往 Model Garden


如要直接從行動和網頁應用程式使用 Gemini,請參閱適用於 Swift、Android、網頁、Flutter 和 Unity 應用程式的 Firebase AI Logic 用戶端 SDK

生成文字

如要測試及疊代即時通訊提示,建議使用Google Cloud 控制台。如要以程式輔助方式將提示傳送至模型,可以使用 REST API、Google Gen AI SDK、Agent Platform SDK,或其中一個其他支援的程式庫和 SDK。

您可以根據特定需求或用途,使用系統指令引導模型行為。舉例來說,您可以為回覆客戶服務要求的聊天機器人定義角色或角色。詳情請參閱系統指令程式碼範例

如果您使用 Gemini 2.5 Flash,可以透過 Google Gen AI SDK 傳送要求。

以下是文字生成範例。

控制台

如要使用 Agent Studio 在Google Cloud 控制台中傳送對話提示,請按照下列步驟操作:

  1. 在控制台的「Agent Platform」部分,前往「Agent Studio」 Google Cloud 頁面。

    前往 Agent Studio

  2. 在「發起對話」中,按一下「文字即時通訊」
  3. 選用步驟:設定模型和參數:

    • 模型:選取「Gemini Pro」
    • 區域:選取要使用的區域。
    • 溫度:使用滑桿或文字方塊輸入溫度值。

      系統會在生成回覆時使用溫度進行取樣,也就是套用 topPtopK 時。溫度參數會決定選取詞元時的隨機程度。如果您想藉由提示生成較不具開放性和創意性的回覆,建議調低溫度參數。另一方面,如果溫度參數較高,則可能產生較多元或有創意的結果。如果溫度參數為 0,模型一律會選取可能性最高的詞元。在這種情況下,特定提示的回覆大多是確定性的,但仍可能出現少量差異。

      如果模型的回覆太普通、太短或提供了備用回覆,再試試看調高 Temperature。如果模型進入無限生成狀態,請將溫度參數調高至至少 0.1,或許能改善結果。

      1.0 是建議的溫度起始值。
    • 輸出權杖限制:使用滑桿或文字方塊輸入輸出上限值。

      回覆內可以生成的詞元數量上限。一個符記約為四個字元。100 個符記約等於 60 到 80 個字。

      如要取得較短的回覆,請指定較低的值;如要取得可能較長的回覆,請調高此值。

    • 新增停止序列:選用。輸入停止序列,也就是包含空格的一連串字元。如果模型遇到停止序列,就會停止回覆生成。停止序列不會包含在回應中,您最多可以新增五個停止序列。
  4. 選用:如要設定進階參數,請按一下「進階」,然後按照下列步驟操作:

    按一下即可展開進階設定

    • Top-K:使用滑桿或文字方塊輸入 Top-K 的值。

      「Top-K」會影響模型選取輸出符記的方式。如果 Top-K 設為 1,代表下一個所選詞元是模型詞彙表的所有詞元中可能性最高者 (也稱為「貪婪解碼」)。如果 Top-K 設為 3,則代表模型會依據 temperature,從可能性最高的 3 個詞元中選取下一個詞元。

      在每個符記選取步驟中,模型會對機率最高的「Top-K」符記取樣,接著進一步根據「Top-P」篩選詞元,最後依 temperature 選出最終詞元。

      如要取得較不隨機的回覆,請指定較低的值;如要取得較隨機的回覆,請調高此值。

    • Top-P:使用滑桿或文字方塊輸入 Top-P 的值。 模型會按照可能性最高到最低的順序選取符記,直到所選符記的可能性總和等於 Top-P 值。如要讓結果的變化性降到最低,請將 Top-P 設為 `0`。
    • 啟用基礎:新增基礎來源路徑,即可自訂這項功能。
  5. 在「文字提示詞」窗格中輸入文字提示。模型會根據先前的訊息內容,生成新的回覆。
  6. 選用:如要顯示文字權杖數量,請按一下「查看權杖」。您可以查看文字提示詞的詞元或詞元 ID。
    • 如要查看文字提示詞中的詞元,這些詞元會以不同顏色醒目顯示,標示各詞元 ID 的分界,請按一下「詞元 ID 對應文字」。不支援媒體權杖。
    • 如要查看權杖 ID,請按一下「權杖 ID」

      如要關閉權杖化工具窗格,請按一下「X」X,或按一下窗格外部。

  7. 按一下「提交」
  8. 選用:如要將提示詞儲存至「我的提示詞」,請按一下 「儲存」
  9. 選用:如要取得提示的 Python 程式碼或 curl 指令,請按一下「取得程式碼」
  10. 選用:如要清除所有先前的訊息,請依序點按 「清除對話」

Python

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考文件

設定環境變數,透過 Vertex AI 使用 Google 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_ENTERPRISE=True

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

Go

瞭解如何安裝或更新 Go

詳情請參閱 SDK 參考文件

設定環境變數,透過 Vertex AI 使用 Google 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_ENTERPRISE=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

安裝

npm install @google/genai

詳情請參閱 SDK 參考文件

設定環境變數,透過 Vertex AI 使用 Google 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_ENTERPRISE=True

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

瞭解如何安裝或更新 Java

詳情請參閱 SDK 參考說明文件

設定環境變數,透過 Vertex AI 使用 Google 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_ENTERPRISE=True


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#

瞭解如何安裝或更新 C#

詳情請參閱 SDK 參考文件

設定環境變數,透過 Vertex AI 使用 Google 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_ENTERPRISE=True


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

使用任何要求資料之前,請先修改下列項目的值:

  • GENERATE_RESPONSE_METHOD:您希望模型生成的回覆類型。 選擇生成模型回覆的傳回方式:
    • streamGenerateContent:在生成回覆時串流傳輸,減少人類觀眾的延遲感。
    • generateContent:系統會在完整生成回應後傳回。
  • LOCATION:處理要求的區域。
  • PROJECT_ID: 您的 [專案 ID](/resource-manager/docs/creating-managing-projects#identifiers)。 。
  • MODEL_ID:要使用的多模態模型 ID。
  • TEXT1
    要加入多輪對話第一個提示的文字指令。例如:What are all the colors in a rainbow?
  • TEXT2
    要納入第二個提示的文字指令。例如:Why does it appear when it rains?
  • TEMPERATURE: 溫度參數用於在回覆生成期間取樣,這會在套用 topPtopK 時發生。溫度參數會決定選取詞元時的隨機程度。如果您想藉由提示生成較不具開放性和創意性的回覆,建議調低溫度參數。另一方面,如果溫度參數較高,則可能產生較多元或有創意的結果。如果溫度參數為 0,模型一律會選取可能性最高的詞元。在這種情況下,特定提示的回覆大多是確定性的,但仍可能出現少量差異。

    如果模型的回覆太普通、太短或提供了備用回覆,再試試看調高 Temperature。如果模型進入無限生成狀態,請將溫度參數調高至至少 0.1,或許能改善結果。

    1.0 是建議的溫度起始值。

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中。 在終端機中執行下列指令,在目前目錄中建立或覆寫這個檔案:

cat > request.json << 'EOF'
{
  "contents": [
    {
      "role": "user",
      "parts": { "text": "TEXT1" }
    },
    {
      "role": "model",
      "parts": { "text": "What a great question!" }
    },
    {
      "role": "user",
      "parts": { "text": "TEXT2" }
    }
  ],
  "generation_config": {
    "temperature": TEMPERATURE
  }
}
EOF

然後執行下列指令,傳送 REST 要求:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD"

PowerShell

將要求主體儲存在名為 request.json 的檔案中。 在終端機中執行下列指令,在目前目錄中建立或覆寫這個檔案:

@'
{
  "contents": [
    {
      "role": "user",
      "parts": { "text": "TEXT1" }
    },
    {
      "role": "model",
      "parts": { "text": "What a great question!" }
    },
    {
      "role": "user",
      "parts": { "text": "TEXT2" }
    }
  ],
  "generation_config": {
    "temperature": TEMPERATURE
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

然後執行下列指令,傳送 REST 要求:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content

您應該會收到類似如下的 JSON 回應。

串流和非串流回應

您可以選擇模型生成串流非串流回覆。如果是串流回覆,系統會在生成輸出權杖後,立即傳送回覆。如果是非串流回覆,所有輸出權杖生成後,您就會收到所有回覆。

以下是串流文字生成範例。

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Agent Platform 快速入門導覽課程」中的 Python 設定說明操作。

如要向 Agent Platform 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。

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

client = genai.Client(http_options=HttpOptions(api_version="v1"))
chat_session = client.chats.create(model="gemini-3.5-flash")

for chunk in chat_session.send_message_stream("Why is the sky blue?"):
    print(chunk.text, end="")
# Example response:
# The
#  sky appears blue due to a phenomenon called **Rayleigh scattering**. Here's
#  a breakdown of why:
# ...

Gemini 多輪對話行為

使用多輪對話時,Gemini Enterprise Agent Platform 會在本機儲存您傳送給模型的初始內容和提示。Gemini Enterprise Agent Platform 會在後續每次向模型發出的要求中,一併傳送所有這些資料。因此,您傳送每則訊息的輸入費用,是已傳送至模型的所有資料的累計總和。如果初始內容夠大,建議您在建立初始模型物件時使用內容快取,以便更妥善地控管輸入成本。

後續步驟