사고

사고 모델은 대답을 생성하기 전에 내부 '사고 과정'을 생성하도록 학습됩니다. 따라서 사고 모델은 사고 능력이 없는 모델보다 더 강력한 추론, 다단계 계획, 수학 문제 해결, 코드 생성이 가능합니다.

사고 과정은 Gemini 모델 전반에서 기본적으로 사용 설정됩니다. Gemini Enterprise Agent Platform에서 Agent Studio를 사용하면 모델의 생성된 대답과 함께 전체 사고 과정을 볼 수 있습니다.

지원되는 모델

사고는 다음 모델에서 지원됩니다.

클릭하여 지원되는 모델 펼치기

모델 사고 제어

모델이 대답을 반환하기 전에 수행하는 사고량을 제어할 수 있습니다. 사고를 제어하는 방법은 모델 버전에 따라 다릅니다.

Gemini 3 이상 모델

Gemini 3 모델에는 사고 예산 구성을 개별 수준으로 간소화하는 thinking_level 파라미터가 도입되었습니다. 복잡한 추론이 필요하지 않은 경우 더 빠르고 지연 시간이 짧은 대답을 위해 모델의 thinking_level를 제한할 수 있습니다.

다음 표에는 각 모델에서 지원되는 thinking_level 값과 각 모델의 기본 thinking_level 값이 요약되어 있습니다.

모델 지원되는 thinking_level 기본값
Gemini 3.8 Flash LOW, MEDIUM, HIGH MEDIUM
Gemini 3.7 Flash LOW, MEDIUM, HIGH MEDIUM
Gemini 3.6 Flash MINIMAL, LOW, MEDIUM, HIGH MEDIUM
Gemini 3.5 Flash-Lite MINIMAL, LOW, MEDIUM, HIGH MINIMAL
Gemini 3.5 Flash MINIMAL, LOW, MEDIUM, HIGH MEDIUM
Gemini 3.1 Pro 프리뷰 LOW, MEDIUM, HIGH HIGH
Gemini 3.1 Flash-Lite 이미지 (Nano Banana 2 Lite) MINIMAL, HIGH MINIMAL
Gemini 3.1 Flash-Lite MINIMAL, LOW, MEDIUM, HIGH MINIMAL
Gemini 3.1 Flash 이미지 MINIMAL, HIGH MINIMAL
Gemini 3 Pro 이미지 HIGH HIGH
Gemini 3 Flash 프리뷰 MINIMAL, LOW, MEDIUM, HIGH HIGH
  • MINIMAL: 모델이 사고에 가능한 한 적은 토큰을 사용하도록 제한하며 광범위한 추론의 이점이 없는 복잡성이 낮은 작업에 가장 적합합니다. Gemini 3.1 Flash-Lite의 기본 수준입니다. MINIMAL은 생각에 대한 예산이 0에 최대한 가깝지만 여전히 생각 서명이 필요합니다. 요청에 사고 서명이 제공되지 않으면 모델에서 400 오류를 반환합니다. 자세한 내용은 생각 서명을 참고하세요.

    from google import genai
    from google.genai import types
    
    client = genai.Client()
    
    response = client.models.generate_content(
        model="gemini-3-flash-preview",
        contents="How does AI work?",
        config=types.GenerateContentConfig(
            thinking_config=types.ThinkingConfig(
                thinking_level=types.ThinkingLevel.MINIMAL
            )
        ),
    )
    print(response.text)
    
  • LOW: 모델이 사고에 더 적은 토큰을 사용하도록 제한하며 광범위한 추론이 필요하지 않은 간단한 작업에 적합합니다. LOW는 속도가 중요한 고처리량 작업에 적합합니다.

    from google import genai
    from google.genai import types
    
    client = genai.Client()
    
    response = client.models.generate_content(
        model="gemini-3.5-flash",
        contents="How does AI work?",
        config=types.GenerateContentConfig(
            thinking_config=types.ThinkingConfig(
                thinking_level=types.ThinkingLevel.LOW
            )
        ),
    )
    print(response.text)
    
  • MEDIUM: 추론이 필요하지만 심층적인 다단계 계획이 필요하지 않은 중간 정도의 복잡성을 가진 작업에 적합한 균형 잡힌 접근 방식을 제공합니다. HIGH보다 지연 시간이 짧으면서 LOW보다 추론 기능이 더 뛰어납니다.

    from google import genai
    from google.genai import types
    
    client = genai.Client()
    
    response = client.models.generate_content(
        model="gemini-3-flash-preview",
        contents="How does AI work?",
        config=types.GenerateContentConfig(
            thinking_config=types.ThinkingConfig(
                thinking_level=types.ThinkingLevel.MEDIUM
            )
        ),
    )
    print(response.text)
    
  • HIGH: 모델이 사고에 더 많은 토큰을 사용할 수 있도록 하며 다단계 계획, 검증된 코드 생성 또는 고급 함수 호출 시나리오와 같이 심층적인 추론이 필요한 복잡한 프롬프트에 적합합니다. Gemini 3 Pro 모델과 Gemini 3 Flash의 기본 수준입니다. 이전에는 전문 추론 모델을 사용했을 수 있는 작업을 대체할 때 이 구성을 사용하세요.

    from google import genai
    from google.genai import types
    
    client = genai.Client()
    
    response = client.models.generate_content(
        model="gemini-3.5-flash",
        contents="Find the race condition in this multi-threaded C++ snippet: [code here]",
        config=types.GenerateContentConfig(
            thinking_config=types.ThinkingConfig(
                thinking_level=types.ThinkingLevel.HIGH
            )
        ),
    )
    print(response.text)
    

Gemini 3 Pro 및 Gemini 3.1 Pro에서는 사고를 사용 중지할 수 없습니다.

Gemini 3 모델에 대한 동일한 요청에서 thinking_levelthinking_budget을 모두 지정하면 모델에서 오류가 반환됩니다.

Gemini 2.5 이하 모델

Gemini 3 이전 모델의 경우 모델이 사고 과정에 사용할 수 있는 토큰 수의 상한을 설정하는 thinking_budget 매개변수를 사용하여 사고를 제어할 수 있습니다. 기본적으로 thinking_budget이 설정되지 않은 경우 모델은 최대 8,192개의 토큰까지 사고하는 정도를 자동으로 제어합니다. API를 통해 동적 예산을 사용하려면 thinking_budget-1로 설정합니다.

기본 사고 예산보다 더 많거나 적은 토큰이 필요할 수 있는 상황에서는 thinking_budget을 수동으로 설정하여 토큰 수에 대한 소프트 상한을 적용할 수 있습니다. 복잡성이 낮은 작업에는 토큰 한도를 낮게, 복잡성이 높은 작업에는 토큰 한도를 높게 설정할 수 있습니다. 이는 소프트 한도이므로 총 사고 토큰이 달라질 수 있습니다. 지연 시간이 더 중요한 경우 예산을 낮추거나 예산을 0으로 설정하여 대답과 함께 사고 콘텐츠가 반환되지 않도록 합니다.

다음 표에서는 지원되는 각 모델에 대해 설정할 수 있는 thinking_budget의 최소 및 최대 금액과 각 모델의 기본 사고 예산을 보여줍니다.

모델 최소 토큰 금액 최대 토큰 금액 기본값
Gemini 2.5 Flash 1 24,576 자동 (최대 8,192개 토큰)
Gemini 2.5 Pro 128 32,768 자동 (최대 8,192개 토큰)
Gemini 2.5 Flash-Lite 512 24,576 자동 (최대 8,192개 토큰)

Gemini 2.5 Flash 및 Gemini 2.5 Flash-Lite를 사용할 때 thinking_budget0으로 설정하면 대답과 함께 사고 콘텐츠가 반환되지 않습니다. 하지만 추론 스타일 텍스트는 모델의 출력에 계속 표시될 수 있습니다. Gemini 2.5 Pro의 경우 사고를 사용 중지할 수 없습니다.

Gemini 3 이전 모델에서 thinking_level 매개변수를 사용하면 모델에서 오류가 반환됩니다.

콘솔

  1. Agent Studio > 프롬프트 만들기를 엽니다.
  2. 모델 패널에서 모델 전환을 클릭하고 메뉴에서 지원되는 모델 중 하나를 선택합니다.
  3. 사고 예산 드롭다운 선택기에서 수동을 선택한 다음 슬라이더를 사용하여 사고 예산 한도를 조정합니다.

Python

설치

pip install --upgrade google-genai

자세한 내용은 SDK 참고 문서를 참고하세요.

Vertex AI에서 Google 생성형 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, ThinkingConfig

client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="solve x^2 + 4x + 4 = 0",
    config=GenerateContentConfig(
        thinking_config=ThinkingConfig(
            thinking_budget=1024,  # Use `0` to turn off thinking
        )
    ),
)

print(response.text)
# Example response:
#     To solve the equation $x^2 + 4x + 4 = 0$, you can use several methods:
#     **Method 1: Factoring**
#     1.  Look for two numbers that multiply to the constant term (4) and add up to the coefficient of the $x$ term (4).
#     2.  The numbers are 2 and 2 ($2 \times 2 = 4$ and $2 + 2 = 4$).
#     ...
#     ...
#     All three methods yield the same solution. This quadratic equation has exactly one distinct solution (a repeated root).
#     The solution is **x = -2**.

# Token count for `Thinking`
print(response.usage_metadata.thoughts_token_count)
# Example response:
#     886

# Total token count
print(response.usage_metadata.total_token_count)
# Example response:
#     1525

Node.js

설치

npm install @google/genai

자세한 내용은 SDK 참고 문서를 참고하세요.

Vertex AI에서 Google 생성형 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 generateWithThoughts(
  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-2.5-flash',
    contents: 'solve x^2 + 4x + 4 = 0',
    config: {
      thinkingConfig: {
        thinkingBudget: 1024,
      },
    },
  });

  console.log(response.text);
  // Example response:
  //  To solve the equation $x^2 + 4x + 4 = 0$, you can use several methods:
  //  **Method 1: Factoring**
  //  1.  Look for two numbers that multiply to the constant term (4) and add up to the coefficient of the $x$ term (4).
  //  2.  The numbers are 2 and 2 ($2 \times 2 = 4$ and $2 + 2 = 4$).
  //  ...
  //  ...
  //  All three methods yield the same solution. This quadratic equation has exactly one distinct solution (a repeated root).
  //  The solution is **x = -2**.

  // Token count for `Thinking`
  console.log(response.usageMetadata.thoughtsTokenCount);
  // Example response:
  //  886

  // Total token count
  console.log(response.usageMetadata.totalTokenCount);
  // Example response:
  //  1525
  return response.text;
}

Go

Go를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 SDK 참고 문서를 참고하세요.

Vertex AI에서 Google 생성형 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"
)

// generateThinkingBudgetContentWithText demonstrates how to generate text including the model's thought process.
func generateThinkingBudgetContentWithText(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"
	thinkingBudget := int32(1024) //Use `0` to turn off thinking
	contents := []*genai.Content{
		{
			Parts: []*genai.Part{
				{Text: "solve x^2 + 4x + 4 = 0"},
			},
			Role: "user",
		},
	}

	resp, err := client.Models.GenerateContent(ctx,
		modelName,
		contents,
		&genai.GenerateContentConfig{
			ThinkingConfig: &genai.ThinkingConfig{
				ThinkingBudget: &thinkingBudget,
			},
		},
	)
	if err != nil {
		return fmt.Errorf("generate content failed: %w", err)
	}

	if resp.UsageMetadata != nil {
		fmt.Fprintf(w, "Thoughts token count: %d\n", resp.UsageMetadata.ThoughtsTokenCount)
		//Example response:
		//  908
		fmt.Fprintf(w, "Total token count: %d\n", resp.UsageMetadata.TotalTokenCount)
		//Example response:
		//  1364
	}

	fmt.Fprintln(w, resp.Text())

	// Example response:
	//    To solve the equation $x^2 + 4x + 4 = 0$, you can use several methods:
	//    **Method 1: Factoring**
	//    1.  Look for two numbers that multiply to the constant term (4) and add up to the coefficient of the $x$ term (4).
	//    2.  The numbers are 2 and 2 ($2 \times 2 = 4$ and $2 + 2 = 4$).
	//    ...
	//    ...
	//    Both methods yield the same result.
	//    The solution to the equation $x^2 + 4x + 4 = 0$ is **$x = -2$**.

	return nil
}

Java

Java를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 SDK 참고 문서를 참고하세요.

Vertex AI에서 Google 생성형 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;
import com.google.genai.types.ThinkingConfig;

public class ThinkingBudgetWithTxt {

  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 controlling the thinking budget
  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()) {

      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .thinkingConfig(ThinkingConfig.builder().thinkingBudget(1024).build())
              .build();

      GenerateContentResponse response =
          client.models.generateContent(modelId, "solve x^2 + 4x + 4 = 0", contentConfig);

      System.out.println(response.text());
      // Example response:
      // To solve the equation $x^2 + 4x + 4 = 0$, we can use several methods:
      //
      // **Method 1: Factoring (Recognizing a Perfect Square Trinomial)**
      //
      // Notice that the left side of the equation is a perfect square trinomial. It fits the form
      // $a^2 + 2ab + b^2 = (a+b)^2$...
      // ...
      // The solution is $x = -2$.

      response
          .usageMetadata()
          .ifPresent(
              metadata -> {
                System.out.println("Token count for thinking: " + metadata.thoughtsTokenCount());
                System.out.println("Total token count: " + metadata.totalTokenCount());
              });
      // Example response:
      // Token count for thinking: Optional[885]
      // Total token count: Optional[1468]
      return response.text();
    }
  }
}

사고 요약 보기

사고 요약은 모델이 대답을 생성하는 동안 실행한 중간 추론 단계를 보여줍니다. Gemini 2.5 이상 모델에서는 사고 요약을 볼 수 있습니다.

Agent Studio에서는 사고 요약이 기본적으로 사용 설정되어 있으며 사고 패널을 펼쳐 확인할 수 있습니다.

API를 사용하는 경우 ThinkingConfig에서 include_thoughts=True를 설정하여 생각 요약을 사용 설정할 수 있습니다.

콘솔

사고 요약은 Agent Studio에서 기본적으로 사용 설정되어 있습니다. 사고 패널을 펼쳐 모델의 요약된 사고 과정을 확인할 수 있습니다.

Python

설치

pip install --upgrade google-genai

자세한 내용은 SDK 참고 문서를 참고하세요.

Vertex AI에서 Google 생성형 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, ThinkingConfig

client = genai.Client()
response = client.models.generate_content(
    model="gemini-3.1-pro-preview",
    contents="solve x^2 + 4x + 4 = 0",
    config=GenerateContentConfig(
        thinking_config=ThinkingConfig(include_thoughts=True)
    ),
)

print(response.text)
# Example Response:
#     Okay, let's solve the quadratic equation x² + 4x + 4 = 0.
#     ...
#     **Answer:**
#     The solution to the equation x² + 4x + 4 = 0 is x = -2. This is a repeated root (or a root with multiplicity 2).

for part in response.candidates[0].content.parts:
    if part and part.thought:  # show thoughts
        print(part.text)
# Example Response:
#     **My Thought Process for Solving the Quadratic Equation**
#
#     Alright, let's break down this quadratic, x² + 4x + 4 = 0. First things first:
#     it's a quadratic; the x² term gives it away, and we know the general form is
#     ax² + bx + c = 0.
#
#     So, let's identify the coefficients: a = 1, b = 4, and c = 4. Now, what's the
#     most efficient path to the solution? My gut tells me to try factoring; it's
#     often the fastest route if it works. If that fails, I'll default to the quadratic
#     formula, which is foolproof. Completing the square? It's good for deriving the
#     formula or when factoring is difficult, but not usually my first choice for
#     direct solving, but it can't hurt to keep it as an option.
#
#     Factoring, then. I need to find two numbers that multiply to 'c' (4) and add
#     up to 'b' (4). Let's see... 1 and 4 don't work (add up to 5). 2 and 2? Bingo!
#     They multiply to 4 and add up to 4. This means I can rewrite the equation as
#     (x + 2)(x + 2) = 0, or more concisely, (x + 2)² = 0. Solving for x is now
#     trivial: x + 2 = 0, thus x = -2.
#
#     Okay, just to be absolutely certain, I'll run the quadratic formula just to
#     double-check. x = [-b ± √(b² - 4ac)] / 2a. Plugging in the values, x = [-4 ±
#     √(4² - 4 * 1 * 4)] / (2 * 1). That simplifies to x = [-4 ± √0] / 2. So, x =
#     -2 again – a repeated root. Nice.
#
#     Now, let's check via completing the square. Starting from the same equation,
#     (x² + 4x) = -4. Take half of the b-value (4/2 = 2), square it (2² = 4), and
#     add it to both sides, so x² + 4x + 4 = -4 + 4. Which simplifies into (x + 2)²
#     = 0. The square root on both sides gives us x + 2 = 0, therefore x = -2, as
#      expected.
#
#     Always, *always* confirm! Let's substitute x = -2 back into the original
#     equation: (-2)² + 4(-2) + 4 = 0. That's 4 - 8 + 4 = 0. It checks out.
#
#     Conclusion: the solution is x = -2. Confirmed.

Node.js

설치

npm install @google/genai

자세한 내용은 SDK 참고 문서를 참고하세요.

Vertex AI에서 Google 생성형 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 generateWithThoughts(
  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-2.5-pro',
    contents: 'solve x^2 + 4x + 4 = 0',
    config: {
      thinkingConfig: {
        includeThoughts: true,
      },
    },
  });

  console.log(response.text);
  // Example Response:
  //  Okay, let's solve the quadratic equation x² + 4x + 4 = 0.
  //  ...
  //  **Answer:**
  //  The solution to the equation x² + 4x + 4 = 0 is x = -2. This is a repeated root (or a root with multiplicity 2).

  for (const part of response.candidates[0].content.parts) {
    if (part && part.thought) {
      console.log(part.text);
    }
  }

  // Example Response:
  // **My Thought Process for Solving the Quadratic Equation**
  //
  // Alright, let's break down this quadratic, x² + 4x + 4 = 0. First things first:
  // it's a quadratic; the x² term gives it away, and we know the general form is
  // ax² + bx + c = 0.
  //
  // So, let's identify the coefficients: a = 1, b = 4, and c = 4. Now, what's the
  // most efficient path to the solution? My gut tells me to try factoring; it's
  // often the fastest route if it works. If that fails, I'll default to the quadratic
  // formula, which is foolproof. Completing the square? It's good for deriving the
  // formula or when factoring is difficult, but not usually my first choice for
  // direct solving, but it can't hurt to keep it as an option.
  //
  // Factoring, then. I need to find two numbers that multiply to 'c' (4) and add
  // up to 'b' (4). Let's see... 1 and 4 don't work (add up to 5). 2 and 2? Bingo!
  // They multiply to 4 and add up to 4. This means I can rewrite the equation as
  // (x + 2)(x + 2) = 0, or more concisely, (x + 2)² = 0. Solving for x is now
  // trivial: x + 2 = 0, thus x = -2.
  //
  // Okay, just to be absolutely certain, I'll run the quadratic formula just to
  // double-check. x = [-b ± √(b² - 4ac)] / 2a. Plugging in the values, x = [-4 ±
  // √(4² - 4 * 1 * 4)] / (2 * 1). That simplifies to x = [-4 ± √0] / 2. So, x =
  // -2 again – a repeated root. Nice.
  //
  // Now, let's check via completing the square. Starting from the same equation,
  // (x² + 4x) = -4. Take half of the b-value (4/2 = 2), square it (2² = 4), and
  // add it to both sides, so x² + 4x + 4 = -4 + 4. Which simplifies into (x + 2)²
  // = 0. The square root on both sides gives us x + 2 = 0, therefore x = -2, as
  //  expected.
  //
  // Always, *always* confirm! Let's substitute x = -2 back into the original
  // equation: (-2)² + 4(-2) + 4 = 0. That's 4 - 8 + 4 = 0. It checks out.
  //
  // Conclusion: the solution is x = -2. Confirmed.

  return response.text;
}

Go

Go를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 SDK 참고 문서를 참고하세요.

Vertex AI에서 Google 생성형 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"
)

// generateContentWithThoughts demonstrates how to generate text including the model's thought process.
func generateContentWithThoughts(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-pro"
	contents := []*genai.Content{
		{
			Parts: []*genai.Part{
				{Text: "solve x^2 + 4x + 4 = 0"},
			},
			Role: "user",
		},
	}

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

	if len(resp.Candidates) == 0 || resp.Candidates[0].Content == nil {
		return fmt.Errorf("no content was generated")
	}

	// The response may contain both the final answer and the model's thoughts.
	// Iterate through the parts to print them separately.
	fmt.Fprintln(w, "Answer:")
	for _, part := range resp.Candidates[0].Content.Parts {
		if part.Text != "" && !part.Thought {
			fmt.Fprintln(w, part.Text)
		}
	}
	fmt.Fprintln(w, "\nThoughts:")
	for _, part := range resp.Candidates[0].Content.Parts {
		if part.Thought {
			fmt.Fprintln(w, part.Text)
		}
	}

	// Example response:
	//  Answer:
	//	Of course! We can solve this quadratic equation in a couple of ways.
	//
	//### Method 1: Factoring (the easiest method for this problem)
	//
	//1.  **Recognize the pattern.** The expression `x² + 4x + 4` is a perfect square trinomial. It fits the pattern `a² + 2ab + b² = (a + b)²`. In this case, `a = x` and `b = 2`.
	//
	//2.  **Factor the equation.**
	//    `x² + 4x + 4 = (x + 2)(x + 2) = (x + 2)²`
	//
	//3.  **Solve for x.** Now set the factored expression to zero:
	//    `(x + 2)² = 0`
	//
	//    Take the square root of both sides:
	//    `x + 2 = 0`
	//
	//    Subtract 2 from both sides:
	//    `x = -2`
	//
	//This type of solution is called a "repeated root" or a "double root" because the factor `(x+2)` appears twice.
	//
	//---
	//
	//### Method 2: Using the Quadratic Formula
	//
	//You can use the quadratic formula for any equation in the form `ax² + bx + c = 0`.
	//
	//The formula is: `x = [-b ± sqrt(b² - 4ac)] / 2a`
	//
	//1.  **Identify a, b, and c.**
	//    *   a = 1
	//    *   b = 4
	//    *   c = 4
	//
	//2.  **Plug the values into the formula.**
	//    `x = [-4 ± sqrt(4² - 4 * 1 * 4)] / (2 * 1)`
	//
	//3.  **Simplify.**
	//    `x = [-4 ± sqrt(16 - 16)] / 2`
	//    `x = [-4 ± sqrt(0)] / 2`
	//    `x = -4 / 2`
	//
	//4.  **Solve for x.**
	//    `x = -2`
	//Alright, the user wants to solve the quadratic equation `x² + 4x + 4 = 0`. My first instinct is to see if I can factor it; that's often the fastest approach if it works.  Looking at the coefficients, I see `a = 1`, `b = 4`, and `c = 4`.  Factoring is clearly the most direct path here. I need to find two numbers that multiply to 4 (c) and add up to 4 (b). Hmm, let's see 1 and 4? Nope, that adds to 5.  2 and 2? Perfect!  2 times 2 is 4, and 2 plus 2 is also 4.
	//
	//So, `x² + 4x + 4` factors nicely into `(x + 2)(x + 2)`.  Ah, a perfect square trinomial! That's useful to note. Now, I can write the equation as `(x + 2)² = 0`.  Taking the square root of both sides gives me `x + 2 = 0`.  And finally, subtracting 2 from both sides, I get `x = -2`.  That's the solution.
	//
	//Just to be thorough, and maybe to offer an alternative explanation, let's verify this using the quadratic formula. It's `x = [-b ± (b² - 4ac)] / 2a`. Plugging in my values:  `x = [-4 ± (4² - 4 * 1 * 4)] / (2 * 1)`.  That simplifies to `x = [-4 ± (16 - 16)] / 2`, or `x = [-4 ± 0] / 2`.  Therefore, `x = -2`. The discriminant being zero tells me I have exactly one real, repeated root.  Great. So, whether I factor or use the quadratic formula, the answer is the same.
	return nil
}

Java

Java를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 SDK 참고 문서를 참고하세요.

Vertex AI에서 Google 생성형 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.Candidate;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.ThinkingConfig;

public class ThinkingIncludeThoughtsWithTxt {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-pro";
    generateContent(modelId);
  }

  // Generates text including thoughts in the response
  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()) {

      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .thinkingConfig(ThinkingConfig.builder().includeThoughts(true).build())
              .build();

      GenerateContentResponse response =
          client.models.generateContent(modelId, "solve x^2 + 4x + 4 = 0", contentConfig);

      System.out.println(response.text());
      // Example response:
      // We can solve the equation x² + 4x + 4 = 0 using a couple of common methods.
      //
      // ### Method 1: Factoring (The Easiest Method for this Problem)
      // **Recognize the pattern:** The pattern for a perfect square trinomial
      // is a² + 2ab + b² = (a + b)².
      // ...
      // ### Final Answer:
      // The solution is **x = -2**.

      // Get parts of the response and print thoughts
      response
          .candidates()
          .flatMap(candidates -> candidates.stream().findFirst())
          .flatMap(Candidate::content)
          .flatMap(Content::parts)
          .ifPresent(
              parts -> {
                parts.forEach(
                    part -> {
                      if (part.thought().orElse(false)) {
                        part.text().ifPresent(System.out::println);
                      }
                    });
              });
      // Example response:
      // Alright, let's break down this quadratic equation, x² + 4x + 4 = 0. My initial thought is,
      // "classic quadratic."  I'll need to find the values of 'x' that make this equation true. The
      // equation is in standard form, and since the coefficients are relatively small, I
      // immediately suspect that factoring might be the easiest route.  It's worth checking.
      //
      // First, I assessed what I had. *a* is 1, *b* is 4, and *c* is 4. I consider my toolkit.
      // Factoring is the likely first choice, then I can use the quadratic formula as a backup,
      // because that ALWAYS works, and I could use graphing. However, for this, factoring seems the
      // cleanest approach.
      //
      // Okay, factoring. I need two numbers that multiply to *c* (which is 4) and add up to *b*
      // (also 4).  I quickly run through the factor pairs of 4: (1, 4), (-1, -4), (2, 2), (-2, -2).
      //  Aha! 2 and 2 fit the bill. They multiply to 4 *and* add up to 4.  Therefore, I can rewrite
      // the equation as (x + 2)(x + 2) = 0.  That simplifies to (x + 2)² = 0. Perfect square
      // trinomial  nice and tidy. Seeing that pattern from the outset can save a step or two. Now,
      // to solve for *x*:  if (x + 2)² = 0, then x + 2 must equal 0.  Therefore, x = -2. Done.
      //
      // But, for the sake of a full explanation, let's use the quadratic formula as a second
      // method. It's a reliable way to double-check the answer, plus it's good practice.  I plug my
      // *a*, *b*, and *c* values into the formula: x = [-b ± (b² - 4ac)] / (2a). That gives me  x
      // = [-4 ± (4² - 4 * 1 * 4)] / (2 * 1). Simplifying under the radical, I get x = [-4 ± (16 -
      // 16)] / 2. So, x = [-4 ± 0] / 2. The square root of 0 is zero, which is very telling!  When
      // the discriminant (b² - 4ac) is zero, you get one real solution, a repeated root. This means
      // x = -4 / 2, which simplifies to x = -2.  Exactly the same as before.
      //
      // Therefore, the answer is x = -2.  Factoring was the most straightforward route.  For
      // completeness, I showed the solution via the quadratic formula, too. Both approaches lead to
      // the same single solution.  This is a repeated root  a double root, if you will.
      //
      // And to be absolutely sure...let's check our answer! Substitute -2 back into the original
      // equation. (-2)² + 4(-2) + 4 = 4 - 8 + 4 = 0.  Yep, 0 = 0. The solution is correct.
      return response.text();
    }
  }
}

다음 시나리오에서는 응답에 생각 요약 텍스트 없이 생각 서명이 포함될 수 있습니다.

  • 복잡성이 낮은 요청: 모델이 대답을 구성하는 데 필요한 추론 단계가 최소한입니다.
  • 요약 사용 중지됨: 생각 요약이 요청되지 않았거나 명시적으로 사용 중지되었습니다.
  • 텍스트가 아닌 추론 모달리티: 특정 모달리티 (예: 이미지 처리)는 텍스트 요약을 내보내지 않을 수 있습니다.

애플리케이션은 항상 관련 생각 서명을 유지하면서 생각 요약 콘텐츠가 없거나 비어 있는 응답을 적절하게 처리해야 합니다.

생각 서명

생각 서명은 모델의 내부 사고 과정을 암호화한 표현으로, 특히 함수 호출을 사용할 때 여러 차례 대화 중에 Gemini 추론 상태를 유지합니다.

모델이 여러 차례의 대화에서 전체 컨텍스트를 유지하도록 하려면 사용된 사고 수준과 관계없이 후속 요청에서 이전 응답의 생각 서명을 반환해야 합니다. 공식 Google 생성형 AI SDK (Python, Node.js, Go 또는 Java)를 사용하고 표준 채팅 기록 기능을 사용하거나 전체 모델 응답을 기록에 추가하는 경우 사고 서명이 자동으로 처리됩니다.

자세한 규칙, 예시, 멀티턴 워크플로 패턴은 생각 서명을 참고하세요.

프롬프트 작성 기법

효과적인 프롬프트 설계를 통해 모델 추론을 유도하고, 토큰 예산을 확보하고, 사고 모델로 최적의 출력 품질을 달성할 수 있습니다.

포괄적인 전략, 멀티샷 패턴, 검증 프롬프트, 디버깅 팁은 프롬프트 사고 가이드를 참고하세요.

가격 책정

모델의 사고 과정에서 생성된 토큰에 대해 요금이 청구됩니다. Gemini 3 Pro, Gemini 2.5 Pro와 같은 일부 모델의 경우 사고가 기본적으로 사용 설정되어 있으며 이러한 토큰에 대해 요금이 청구됩니다.

자세한 내용은 Agent Platform 가격 책정을 참고하세요. 비용을 관리하는 방법을 알아보려면 모델 사고 제어를 참고하세요.

다음 단계

가이드

사고 서명을 사용하여 멀티턴 및 다단계 대화 중에 Gemini 추론 상태를 유지하는 방법을 알아보세요.

가이드

Gemini 사고 모델에 맞게 조정된 프롬프트 엔지니어링 기법과 권장사항을 살펴봅니다.

콘솔

Google Cloud 콘솔에서 직접 Gemini에 프롬프트를 입력해 보세요.