內容產生參數

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

權杖取樣參數

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

Top-P

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

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

詳情請參閱「topP」。

溫度參數

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

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

1.0 是建議的溫度起始值。

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

停止參數

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

輸出詞元數量上限

設定 maxOutputTokens,限制回覆中生成的權杖數量。一個符記約為四個字元,因此 100 個符記大約相當於 60 到 80 個字。將值設為偏低,即可限制回覆長度。

停止序列

stopSequences 中定義字串,讓模型在回應中遇到其中一個字串時停止生成文字。如果字串在回應中出現多次,系統會在第一次遇到該字串時截斷回應。字串會區分大小寫。

權杖懲處參數

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

頻率處罰

正值會懲罰在生成的文字中重複出現的符記,降低重複內容的機率。最小值為 -2.0。最大值為 2.0,但不包括 2.0。詳情請參閱「frequencyPenalty」。

狀態處罰

正值會懲罰已出現在生成文字中的符記,提高生成更多元內容的機率。最小值為 -2.0。最大值為 2.0,但不包括 2.0。詳情請參閱「presencePenalty」。

進階參數

使用這些參數可在回應中傳回更多有關權杖的資訊,或控管回應的變異性。

輸出符記的記錄機率

在每個生成步驟中,傳回最有可能的候選符記的記錄機率。模型在每個步驟中選擇的符記,可能與最有可能的候選符記不同。請使用 120 範圍內的整數值,指定要傳回的候選人數。詳情請參閱 logprobs。您也需要將 responseLogprobs 參數設為 true,才能使用這項功能。

responseLogprobs 參數會傳回模型在每個步驟中選擇的符記記錄機率。

詳情請參閱「Logprobs 簡介」筆記本。

種子

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

範例

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

Python

安裝

pip install --upgrade google-genai

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

設定環境變數,透過 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

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-2.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 使用 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"

	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://googleapis.github.io/python-genai/genai.html#genai.types.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 使用 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

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 使用 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 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();
    }
  }
}

後續步驟