内容生成参数

本页面显示了您可以在向模型发出的请求中设置的可选采样参数。每个模型的可用参数可能有所不同。如需了解详情,请参阅 参考文档

token 采样参数

本部分中的参数会影响模型从其词汇表中选择下一个 token 的方式。通过调整这些参数,您可以控制所生成文本的随机性和多样性。

Top-P

Top-P 可更改模型选择输出词元的方式。系统会按照概率从最高到最低的顺序选择 token,直到所选 token 的概率总和等于 top-P 值。例如,如果词元 A、B 和 C 的概率分别为 0.3、0.2 和 0.1,并且 top-P 值为 0.5,则模型将选择 A 或 B 作为下一个词元(通过温度确定),并会排除 C,将其作为候选词元。

指定较低的值可获得随机程度较低的回答,指定较高的值可获得随机程度较高的回答。

如需了解详情,请参阅 topP

温度

温度 (temperature) 在生成回复期间用于采样,在应用 topPtopK 时会生成回复。温度可以控制词元选择的随机性。 较低的温度有利于需要更少开放性或创造性回复的提示,而较高的温度可以带来更具多样性或创造性的结果。温度为 0 表示始终选择概率最高的词元。在这种情况下,给定提示的回复大多是确定的,但可能仍然有少量变化。

如果模型返回的回答过于笼统、过于简短,或者模型给出后备回答,请尝试提高温度。 如果模型进入无限生成状态,将温度提高到至少 0.1 可能会改善结果。

1.0 是建议的温度初始值。

较低的温度会产生可预测(但并非完全确定性)的结果。如需了解详情,请参阅 temperature

停止参数

通过本部分中的参数,您可以定义生成过程应停止的条件,从而精确控制模型生成的输出的长度和内容。

输出词元数上限

设置 maxOutputTokens 以限制回答中生成的 token 数量。一个 token 约为 4 个字符,因此 100 个 token 大约对应 60-80 个字词。设置较低的值可限制回答的长度。

停止序列

stopSequences 中定义字符串,告知模型在回答中遇到其中一个字符串时,停止生成文本。如果某个字符串在回答中多次出现,则回答会在首次出现该字符串的位置截断。字符串区分大小写。

token 惩罚参数

本部分中的参数可让您根据 token 在输出中的频率和存在情况,控制生成 token 的可能性。

频次惩罚

正值会惩罚生成的文本中反复出现的词元,从而降低重复内容概率。最小值为 -2.0。最大值为 2.0,但不包括该数值。 如需了解详情,请参阅 frequencyPenalty 文档中的 GenerationConfig

存在性惩罚

正值会惩罚已生成文本中已存在的词元,从而增加生成更多样化内容的概率。最小值为 -2.0。最大值为 2.0,但不包括该数值。 如需了解详情,请参阅 presencePenalty 文档中的 GenerationConfig

高级参数

您可以使用这些参数在回答中返回有关 token 的更多信息,或控制回答的可变性。

种子

当种子固定为特定值时,模型会尽最大努力为重复请求提供相同的回答。无法保证确定性输出。此外,更改模型或参数设置(例如温度)可能会导致回答发生变化,即使您使用相同的种子值也是如此。默认情况下,系统会使用随机种子值。 如需了解详情,请参阅 seed

示例

以下示例展示了如何使用参数来调优模型的回答。

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Google Gen AI SDK 与 Vertex AI 搭配使用:

# 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 参考文档

设置环境变量以将 Google Gen AI SDK 与 Vertex AI 搭配使用:

# 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 参考文档

设置环境变量以将 Google Gen AI SDK 与 Vertex AI 搭配使用:

# 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 参考文档

设置环境变量以将 Google Gen AI SDK 与 Vertex AI 搭配使用:

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

后续步骤