コンテンツ生成パラメータ

このページでは、モデルへのリクエストで設定できる省略可能なサンプリング パラメータについて説明します。使用可能なパラメータはモデルによって異なることがあります。詳細については、リファレンス ドキュメントをご覧ください。

トークン サンプリング パラメータ

Top-P

Top-P は、モデルが出力用にトークンを選択する方法を変更します。トークンは、確率の合計が Top-P 値に等しくなるまで、確率の高いものから低いものへと選択されます。たとえば、トークン A、B、C の確率が 0.3、0.2、0.1 で、Top-P 値が 0.5 だとします。このとき、モデルは次のトークンとして A か B を温度を使って選択し、C は候補から外します。

ランダムなレスポンスを減らしたい場合は小さい値を、ランダムなレスポンスを増やしたい場合は大きい値を指定します。

詳細については、topP をご覧ください。

温度

温度は、レスポンス生成時のサンプリングに使用されます。レスポンス生成は、topPtopK が適用された場合に発生します。温度は、トークン選択のランダム性の度合いを制御します。温度が低いほど、確定的で自由度や創造性を抑えたレスポンスが求められるプロンプトに適しています。一方、温度が高いと、より多様で創造的な結果を導くことができます。温度が 0 の場合、確率が最も高いトークンが常に選択されます。この場合、特定のプロンプトに対するレスポンスはほとんど確定的ですが、わずかに変動する可能性は残ります。

モデルが返すレスポンスが一般的すぎる、短すぎる、あるいはフォールバック(代替)レスポンスが返ってくる場合は、温度を高く設定してみてください。

温度が低くなるほど、予測可能な(ただし、完全に決定的ではない)結果が得られます。詳細については、temperature をご覧ください。

停止パラメータ

最大出力トークン

maxOutputTokens を設定して、レスポンスで生成されるトークンの数を制限します。1 つのトークンは約 4 文字なので、100 トークンは約 60~80 語に相当します。レスポンスの長さを制限するには、小さい値を設定します。

停止シーケンス

stopSequences に文字列を定義し、レスポンスでいずれかの文字列が検出された場合に、テキストの生成を停止するようモデルに指示します。レスポンスで文字列が複数回出現する場合、文字列が最初に見つかった箇所でレスポンスが切り捨てられます。文字列は大文字と小文字が区別されます。

トークン ペナルティ パラメータ

頻度ペナルティ

値が正の場合は、生成されたテキストに繰り返し出現するトークンにペナルティが課されるため、コンテンツが繰り返される確率は低下します。最小値は -2.0 です。最大値は 2.0 の手前の値です。 詳細については、frequencyPenalty をご覧ください。

プレゼンス ペナルティ

値が正の場合は、生成されたテキスト内の既存のトークンにペナルティが課されるため、より多様なコンテンツが生成される確率は高くなります。最小値は -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();
    }
  }
}

次のステップ