內容生成參數

本頁面說明在向模型提出要求時,可以設定的選用取樣參數。每個模型可用的參數不盡相同。詳情請參閱參考文件。

權杖取樣參數

本節中的參數會影響模型如何從詞彙中選取下一個詞元。調整這些參數,即可控制生成的文字的隨機性和多樣性。

Top-K

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

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

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

Gemini 3.5 Flash 的 topK 固定為 64,無法修改。

詳情請參閱「topK」。

Top-P

「Top-P」會影響模型選取輸出符記的方式。模型會按照機率最高到最低的順序選取詞元,直到所選詞元的機率總和等於 Top-P 值。舉例來說,假設詞元 A、B 和 C 的可能性分別為 0.3、0.2 和 0.1,而 Top-P 值為 0.5,模型會依據溫度參數選擇 A 或 B 做為下一個詞元,並排除 C。

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

詳情請參閱「topP」。

溫度參數

溫度用於在生成回覆時進行取樣,這會在套用 topP 和 topK 時發生。溫度參數會決定選取詞元時的隨機程度。如果您想藉由提示生成較不具開放性和創意性的回覆,建議調低溫度參數。另一方面,如果溫度參數較高,則可能產生較多元或有創意的結果。如果溫度參數為 0,模型一律會選取可能性最高的詞元。在這種情況下,特定提示的回覆大多是確定的,但仍可能有些微變化。

如果模型的回覆太普通、太短或提供了備用回覆,再試試看調高 Temperature。如果模型進入無限生成狀態,將溫度提高到至少 0.1,可能會有更好的結果。

1.0 是建議的溫度起始值。

溫度越低,結果越可預測 (但並非完全確定)。詳情請參閱「temperature」。

停止參數

本節的參數可讓您定義生成程序應停止的條件,精確控制模型生成輸出的長度和內容。

輸出詞元數量上限

設定 maxOutputTokens,限制回覆中生成的詞元數量。一個詞元約為四個字元,因此 100 個詞元約為 60 到 80 個字。設定較低的值,可限制回覆長度。

停止序列

在 stopSequences 中定義字串,指示模型在回覆中遇到其中一個字串時,停止生成文字。如果字串在回應中出現多次,則回應會在首次出現該字串的位置截斷。字串會區分大小寫。

詞元懲罰參數

本節中的參數可讓您根據輸出內容中詞元的頻率和存在與否,控制詞元生成的可能性。

頻率懲罰

正值會對生成的文字中重複出現的詞元進行懲罰,降低內容重複的機率。最小值為 -2.0。最大值不得超過 2.0。詳情請參閱GenerationConfig說明文件中的frequencyPenalty。

存在懲罰

正值會對已出現在生成的文字中的詞元進行懲罰,提高生成更多樣化內容的可能性。最小值為 -2.0。最大值不得超過 2.0 (不含)。詳情請參閱GenerationConfig說明文件中的presencePenalty。

回應格式參數

本節中的參數可用於設定模型生成輸出的格式。

回覆 MIME 類型

設定 responseMimeType,指定生成候選文字的輸出回覆 MIME 類型。支援的值包括:

  • text/plain (預設):純文字輸出。
  • application/json:候選項目中的 JSON 回覆。
  • text/x.enum:如果是分類工作,請輸出回覆結構定義中定義的列舉值。

請指定適當的回應類型,避免發生非預期的行為。舉例來說,如果您需要 JSON 格式的回應,請指定 application/json,而非 text/plain。

詳情請參閱「responseMimeType」和「結構化輸出內容」。

進階參數

使用這些參數,可傳回更多有關回應中權杖的資訊,或控制回應的變化程度。

候選項目數量

要傳回的回覆變化版本數量。系統會根據每項要求,向您收取所有候選輸出詞元的費用,但輸入詞元只會收費一次。

指定多個候選項目是預先發布版功能,適用於 generateContent (不支援 streamGenerateContent)。

詳情請參閱「candidateCount」。

種子

如果將種子設為特定值,模型會盡可能為重複的要求提供相同回覆。不保證一定會產生確定性輸出內容。此外,即便採用相同的種子值,如果變更模型或參數設定 (例如 temperature),回覆還是有可能不同。根據預設,系統會使用隨機種子值。詳情請參閱「seed」。

範例

以下範例說明如何使用參數調整模型的回覆。

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 GenerateContentConfig, HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="Why is the sky blue?",
    # See the SDK documentation at
    # https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentConfig
    config=GenerateContentConfig(
        temperature=0,
        candidate_count=1,
        response_mime_type="application/json",
        top_p=0.95,
        top_k=20,
        seed=5,
        max_output_tokens=500,
        stop_sequences=["STOP!"],
        presence_penalty=0.0,
        frequency_penalty=0.0,
    ),
)
print(response.text)
# Example response:
# {
#   "explanation": "The sky appears blue due to a phenomenon called Rayleigh scattering. When ...
# }

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"

	genai "google.golang.org/genai"
)

// generateWithConfig shows how to generate text using a text prompt and custom configuration.
func generateWithConfig(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.Text("Why is the sky blue?")
	// See the documentation: https://pkg.go.dev/google.golang.org/genai#GenerateContentConfig
	config := &genai.GenerateContentConfig{
		Temperature:      genai.Ptr(float32(0.0)),
		CandidateCount:   int32(1),
		ResponseMIMEType: "application/json",
	}

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

	respText := resp.Text()

	fmt.Fprintln(w, respText)
	// Example response:
	// {
	//   "explanation": "The sky is blue due to a phenomenon called Rayleigh scattering ...
	// }

	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 config = {
    temperature: 0,
    candidateCount: 1,
    responseMimeType: 'application/json',
    topP: 0.95,
    topK: 20,
    seed: 5,
    maxOutputTokens: 500,
    stopSequences: ['STOP!'],
    presencePenalty: 0.0,
    frequencyPenalty: 0.0,
  };

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: 'Why is the sky blue?',
    config: config,
  });

  console.log(response.text);

  // Example response:
  // {
  //   "explanation": "The sky appears blue due to a phenomenon called Rayleigh scattering. When ...
  // }

  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.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;

public class TextGenerationConfigWithText {

  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 and optional configurations
  public static String generateContent(String modelId) {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // Set optional configuration parameters
      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .temperature(0.0F)
              .candidateCount(1)
              .responseMimeType("application/json")
              .topP(0.95F)
              .topK(20F)
              .seed(5)
              .maxOutputTokens(500)
              .stopSequences("STOP!")
              .presencePenalty(0.0F)
              .frequencyPenalty(0.0F)
              .build();

      // Generate content using optional configuration
      GenerateContentResponse response =
          client.models.generateContent(modelId, "Why is the sky blue?", contentConfig);

      System.out.print(response.text());
      // Example response:
      // {
      //  "explanation": "The sky appears blue due to a phenomenon called Rayleigh scattering.
      // Sunlight, which appears white, is actually composed of all the colors of the rainbow...
      // }
      return response.text();
    }
  }
}

後續步驟