생각 중

Gemini 2.5 모델은 추론 및 다단계 계획 수립 능력을 크게 향상하는 내부 '사고 과정'을 사용할 수 있으므로 코딩, 고급 수학, 데이터 분석과 같은 복잡한 작업에 매우 효과적입니다.

사고 모델은 다음 구성과 옵션을 제공합니다.

  • 사고 예산: 사고 예산을 사용하여 모델이 수행할 수 있는 '사고'의 양을 구성할 수 있습니다. 이 구성은 지연 시간이나 비용을 줄이는 것이 우선인 경우 특히 중요합니다. 또한 작업 난이도 비교를 검토하여 모델에 사고 능력이 얼마나 필요한지 결정하세요.

  • 생각 요약: 생각 요약을 사용 설정하여 생성된 대답에 포함할 수 있습니다. 이러한 요약은 모델의 원시적인 생각을 종합한 버전이며 모델의 내부 추론 프로세스에 대한 통찰력을 제공합니다.

  • 사고 서명: Firebase AI Logic SDK는 사고 서명을 자동으로 처리하므로 함수 호출을 사용할 때 특히 모델이 이전 턴의 사고 컨텍스트에 액세스할 수 있습니다.

사고 모델 사용에 관한 권장사항 및 프롬프트 안내를 검토하세요.

사고 모델 사용

다른 Gemini 모델을 사용하는 것과 마찬가지로 사고 모델을 사용하세요(선택한 Gemini API 제공업체를 초기화하고 GenerativeModel 인스턴스를 만드는 등). 이러한 모델은 구조화된 출력 생성 또는 멀티모달 입력 (예: 이미지, 동영상, 오디오, PDF) 분석과 같은 텍스트 또는 코드 생성 작업에 사용할 수 있습니다. 출력을 스트리밍할 때도 사고 모델을 사용할 수 있습니다.

이 기능을 지원하는 모델

Gemini 2.5 모델만 이 기능을 지원합니다.

  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite

사고 모델 사용을 위한 권장사항 및 프롬프트 안내

전체 사고 과정을 확인할 수 있는 Google AI Studio 또는 Vertex AI Studio에서 프롬프트를 테스트하는 것이 좋습니다. 모델이 잘못된 방향으로 나아간 부분을 파악하여 프롬프트를 개선하여 더 일관되고 정확한 대답을 얻을 수 있습니다.

원하는 결과를 설명하는 일반적인 프롬프트로 시작하여 모델이 대답을 결정하는 방법에 관한 초기 생각을 관찰합니다. 대답이 예상과 다른 경우 다음 프롬프트 기법 중 하나를 사용하여 모델이 더 나은 대답을 생성하도록 지원하세요.

  • 단계별 안내 제공하기
  • 입력-출력 쌍의 여러 예시 제공
  • 출력과 대답의 문구와 형식을 지정하는 방법에 관한 안내를 제공합니다.
  • 구체적인 인증 단계 제공

프롬프트 외에도 다음 권장사항을 사용하는 것이 좋습니다.

  • 시스템 안내를 설정합니다. 시스템 안내는 모델이 프롬프트 또는 최종 사용자의 추가 안내를 받기 전에 추가하는 '서문'과 같습니다. 이를 통해 특정 요구사항 및 사용 사례에 따라 모델의 동작을 조정할 수 있습니다.

  • 사고 예산을 설정하여 모델이 수행할 수 있는 사고량을 구성합니다. 예산을 낮게 설정하면 모델이 대답을 '과도하게 생각'하지 않습니다. 예산을 높게 설정하면 필요한 경우 모델이 더 많이 생각할 수 있습니다. 사고 예산을 설정하면 실제 대답에 더 많은 총 토큰 출력 한도가 할당됩니다.

  • Firebase 콘솔에서 AI 모니터링을 사용 설정하여 사고가 사용 설정된 요청의 사고 토큰 수와 지연 시간을 모니터링합니다. 생각 요약을 사용 설정한 경우 콘솔에 표시되며, 여기에서 모델의 자세한 추론을 검사하여 프롬프트를 디버그하고 개선할 수 있습니다.

사고 예산 제어

모델이 대답을 생성하기 위해 수행할 수 있는 사고량을 제어하려면 사용할 수 있는 사고 예산 토큰 수를 지정하면 됩니다.

기본 사고 예산보다 토큰이 더 많거나 적게 필요한 상황에서는 사고 예산을 수동으로 설정할 수 있습니다. 작업 복잡성 및 추천 예산에 관한 자세한 안내는 이 섹션의 뒷부분을 참고하세요. 다음은 대략적인 안내입니다.

  • 지연 시간이 중요하거나 복잡성이 낮은 작업의 경우 사고 예산을 낮게 설정하세요.
  • 복잡한 작업에는 사고 예산을 높게 설정하세요.

사고 예산 설정

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다.

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig의 사고 예산을 설정합니다. 구성은 인스턴스의 수명 동안 유지됩니다. 요청마다 다른 사고 예산을 사용하려면 각 예산으로 구성된 GenerativeModel 인스턴스를 만드세요.

이 섹션의 뒷부분에서 지원되는 사고 예산 값에 대해 알아보세요.

Swift

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 사고 예산을 설정합니다.


// ...

// Set the thinking configuration
// Use a thinking budget value appropriate for your model (example value shown here)
let generationConfig = GenerationConfig(
  thinkingConfig: ThinkingConfig(thinkingBudget: 1024)
)

// Specify the config as part of creating the `GenerativeModel` instance
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  generationConfig: generationConfig
)

// ...

Kotlin

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig의 매개변수 값을 설정합니다.


// ...

// Set the thinking configuration
// Use a thinking budget value appropriate for your model (example value shown here)
val generationConfig = generationConfig {
  thinkingConfig = thinkingConfig {
      thinkingBudget = 1024
  }
}

// Specify the config as part of creating the `GenerativeModel` instance
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
  modelName = "GEMINI_MODEL_NAME",
  generationConfig,
)

// ...

Java

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig의 매개변수 값을 설정합니다.


// ...

// Set the thinking configuration
// Use a thinking budget value appropriate for your model (example value shown here)
ThinkingConfig thinkingConfig = new ThinkingConfig.Builder()
    .setThinkingBudget(1024)
    .build();

GenerationConfig generationConfig = GenerationConfig.builder()
    .setThinkingConfig(thinkingConfig)
    .build();

// Specify the config as part of creating the `GenerativeModel` instance
GenerativeModelFutures model = GenerativeModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel(
                  /* modelName */ "GEMINI_MODEL_NAME",
                  /* generationConfig */ generationConfig
                );
);

// ...

Web

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig의 매개변수 값을 설정합니다.


// ...

const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set the thinking configuration
// Use a thinking budget value appropriate for your model (example value shown here)
const generationConfig = {
  thinkingConfig: {
    thinkingBudget: 1024
  }
};

// Specify the config as part of creating the `GenerativeModel` instance
const model = getGenerativeModel(ai, { model: "GEMINI_MODEL_NAME", generationConfig });

// ...

Dart

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig의 매개변수 값을 설정합니다.


// ...

// Set the thinking configuration
// Use a thinking budget value appropriate for your model (example value shown here)
final thinkingConfig = ThinkingConfig(thinkingBudget: 1024);

final generationConfig = GenerationConfig(
  thinkingConfig: thinkingConfig
);

// Specify the config as part of creating the `GenerativeModel` instance
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  config: generationConfig,
);

// ...

Unity

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig의 매개변수 값을 설정합니다.


// ...

// Set the thinking configuration
// Use a thinking budget value appropriate for your model (example value shown here)
var thinkingConfig = new ThinkingConfig(thinkingBudget: 1024);

var generationConfig = new GenerationConfig(
  thinkingConfig: thinkingConfig
);

// Specify the config as part of creating the `GenerativeModel` instance
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  generationConfig: generationConfig
);

// ...

지원되는 사고 예산 값

다음 표에는 모델의 thinkingBudget를 구성하여 각 모델에 설정할 수 있는 사고 예산 값이 나와 있습니다.

모델 기본값 사고 예산의 사용 가능한 범위
사고를 사용 중지할 값

동적 사고를 지원하는 가치
최솟값 최댓값
Gemini 2.5 Pro 8,192 128 32,768 사용 중지할 수 없음 -1
Gemini 2.5 Flash 8,192 1 24,576 0 -1
Gemini 2.5 Flash‑Lite 0
(기본적으로 생각하기가 사용 중지됨)
512 24,576 0
(또는 사고 예산을 전혀 구성하지 않음)
-1

생각 숨기기

더 쉬운 작업의 경우 사고 능력이 필요하지 않으며 기존 추론으로 충분합니다. 또는 지연 시간 감소가 우선순위인 경우 모델이 응답을 생성하는 데 필요한 시간 이상을 사용하지 않도록 할 수 있습니다.

이러한 상황에서는 생각을 사용 중지할 수 있습니다.

  • Gemini 2.5 Pro: 사용 중지할 수 없음
  • Gemini 2.5 Flash: thinkingBudget0 토큰으로 설정
  • Gemini 2.5 Flash‑Lite: 기본적으로 생각하기가 사용 중지됨

동적 사고 사용 설정

thinkingBudget-1로 설정하면 모델이 언제 얼마나 사고할지 (동적 사고라고 함) 결정할 수 있습니다. 모델은 위에 나열된 최대 토큰 값까지 적절하다고 판단되는 만큼의 토큰을 사용할 수 있습니다.

작업 복잡성

  • 쉬운 작업 — 사고를 중단해도 됨
    사실 검색이나 분류와 같이 복잡한 추론이 필요하지 않은 간단한 요청 예를 들면 다음과 같습니다.

    • "DeepMind는 어디에서 설립되었어?"
    • '이 이메일은 회의를 요청하는 건가요, 아니면 정보를 제공하는 건가요?'
  • 중간 작업 - 기본 예산 또는 약간의 추가 사고 예산이 필요함
    단계별 처리 또는 더 깊은 이해가 필요한 일반적인 요청입니다. 예를 들면 다음과 같습니다.

    • '광합성과 성장의 유사점을 만들어 줘.'
    • '전기 자동차와 하이브리드 자동차를 비교 및 대조해 줘.'
  • 어려운 작업 — 최대 사고 예산이 필요할 수 있음
    복잡한 수학 문제 풀기나 코딩 작업과 같은 매우 복잡한 과제 이러한 유형의 작업에서는 모델이 전체 추론 및 계획 기능을 사용해야 하며, 대답을 제공하기 전에 많은 내부 단계를 거치는 경우가 많습니다. 예를 들면 다음과 같습니다.

    • 'AIME 2025의 문제 1을 풀어 줘. 17b가 97b의 약수가 되는 모든 정수 밑 b > 9의 합을 구해야 해.'
    • '사용자 인증을 포함하여 실시간 주식 시장 데이터를 시각화하는 웹 애플리케이션용 Python 코드를 작성해 줘. 최대한 효율적으로 만들어야 해'라고 말했습니다.

대답에 사고 요약 포함

사고 요약은 모델의 원시적인 생각을 합성한 버전으로, 모델의 내부 추론 과정에 대한 유용한 정보를 제공합니다.

대답에 생각 요약을 포함해야 하는 몇 가지 이유는 다음과 같습니다.

  • 앱의 UI에 생각 요약을 표시하거나 사용자에게 액세스 권한을 부여할 수 있습니다. 생각 요약은 앱에서 사용되는 방식을 더 세부적으로 제어할 수 있도록 대답에서 별도의 부분으로 반환됩니다.

  • Firebase 콘솔에서 AI 모니터링을 사용 설정하면 콘솔에 사고 요약이 표시됩니다. 여기에서 모델의 상세한 추론을 검사하여 프롬프트를 디버그하고 개선할 수 있습니다.

다음은 생각 요약에 관한 몇 가지 주요 참고사항입니다.

  • 사고 요약은 사고 예산에 의해 제어되지 않습니다 (예산은 모델의 원시 사고에만 적용됨). 하지만 생각이 사용 중지되어 있으면 모델에서 생각 요약을 반환하지 않습니다.

  • 사고 요약은 모델의 일반 생성 텍스트 응답의 일부로 간주되며 출력 토큰으로 계산됩니다.

사고 요약 사용 설정

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다.

모델 구성에서 includeThoughts를 true로 설정하여 사고 요약을 사용 설정할 수 있습니다. 그런 다음 응답에서 thoughtSummary 필드를 확인하여 요약에 액세스할 수 있습니다.

다음은 응답에서 생각 요약을 사용 설정하고 검색하는 방법을 보여주는 예입니다.

Swift

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
let generationConfig = GenerationConfig(
  thinkingConfig: ThinkingConfig(includeThoughts: true)
)

// Specify the config as part of creating the `GenerativeModel` instance
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  generationConfig: generationConfig
)

let response = try await model.generateContent("solve x^2 + 4x + 4 = 0")

// Handle the response that includes thought summaries
if let thoughtSummary = response.thoughtSummary {
  print("Thought Summary: \(thoughtSummary)")
}
guard let text = response.text else {
  fatalError("No text in response.")
}
print("Answer: \(text)")

Kotlin

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
val generationConfig = generationConfig {
  thinkingConfig = thinkingConfig {
      includeThoughts = true
  }
}

// Specify the config as part of creating the `GenerativeModel` instance
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
  modelName = "GEMINI_MODEL_NAME",
  generationConfig,
)

val response = model.generateContent("solve x^2 + 4x + 4 = 0")

// Handle the response that includes thought summaries
response.thoughtSummary?.let {
    println("Thought Summary: $it")
}
response.text?.let {
    println("Answer: $it")
}

Java

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
ThinkingConfig thinkingConfig = new ThinkingConfig.Builder()
    .setIncludeThoughts(true)
    .build();

GenerationConfig generationConfig = GenerationConfig.builder()
    .setThinkingConfig(thinkingConfig)
    .build();

// Specify the config as part of creating the `GenerativeModel` instance
GenerativeModelFutures model = GenerativeModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel(
                  /* modelName */ "GEMINI_MODEL_NAME",
                  /* generationConfig */ generationConfig
                );
);

// Handle the response that includes thought summaries
ListenableFuture responseFuture = model.generateContent("solve x^2 + 4x + 4 = 0");
Futures.addCallback(responseFuture, new FutureCallback() {
    @Override
    public void onSuccess(GenerateContentResponse response) {
        if (response.getThoughtSummary() != null) {
            System.out.println("Thought Summary: " + response.getThoughtSummary());
        }
        if (response.getText() != null) {
            System.out.println("Answer: " + response.getText());
        }
    }

    @Override
    public void onFailure(Throwable t) {
        // Handle error
    }
}, MoreExecutors.directExecutor());

Web

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
const generationConfig = {
  thinkingConfig: {
    includeThoughts: true
  }
};

// Specify the config as part of creating the `GenerativeModel` instance
const model = getGenerativeModel(ai, { model: "GEMINI_MODEL_NAME", generationConfig });

const result = await model.generateContent("solve x^2 + 4x + 4 = 0");
const response = result.response;

// Handle the response that includes thought summaries
if (response.thoughtSummary()) {
    console.log(`Thought Summary: ${response.thoughtSummary()}`);
}
const text = response.text();
console.log(`Answer: ${text}`);

Dart

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
final thinkingConfig = ThinkingConfig(includeThoughts: true);

final generationConfig = GenerationConfig(
  thinkingConfig: thinkingConfig
);

// Specify the config as part of creating the `GenerativeModel` instance
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  generationConfig: generationConfig,
);

final response = await model.generateContent('solve x^2 + 4x + 4 = 0');

// Handle the response that includes thought summaries
if (response.thoughtSummary != null) {
  print('Thought Summary: ${response.thoughtSummary}');
}
if (response.text != null) {
  print('Answer: ${response.text}');
}

Unity

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
var thinkingConfig = new ThinkingConfig(includeThoughts: true);

var generationConfig = new GenerationConfig(
  thinkingConfig: thinkingConfig
);

// Specify the config as part of creating the `GenerativeModel` instance
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  generationConfig: generationConfig
);

var response = await model.GenerateContentAsync("solve x^2 + 4x + 4 = 0");

// Handle the response that includes thought summaries
if (response.ThoughtSummary != null) {
    Debug.Log($"Thought Summary: {response.ThoughtSummary}");
}
if (response.Text != null) {
    Debug.Log($"Answer: {response.Text}");
}

사고 요약 스트림

generateContentStream를 사용하여 대답을 스트리밍하는 경우 생각 요약을 볼 수도 있습니다. 이렇게 하면 대답 생성 중에 연속적인 증분 요약이 반환됩니다.

Swift

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
let generationConfig = GenerationConfig(
  thinkingConfig: ThinkingConfig(includeThoughts: true)
)

// Specify the config as part of creating the `GenerativeModel` instance
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  generationConfig: generationConfig
)

let stream = try model.generateContentStream("solve x^2 + 4x + 4 = 0")

// Handle the streamed response that includes thought summaries
var thoughts = ""
var answer = ""
for try await response in stream {
  if let thought = response.thoughtSummary {
    if thoughts.isEmpty {
      print("--- Thoughts Summary ---")
    }
    print(thought)
    thoughts += thought
  }

  if let text = response.text {
    if answer.isEmpty {
      print("--- Answer ---")
    }
    print(text)
    answer += text
  }
}

Kotlin

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
val generationConfig = generationConfig {
  thinkingConfig = thinkingConfig {
      includeThoughts = true
  }
}

// Specify the config as part of creating the `GenerativeModel` instance
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
  modelName = "GEMINI_MODEL_NAME",
  generationConfig,
)

// Handle the streamed response that includes thought summaries
var thoughts = ""
var answer = ""
model.generateContentStream("solve x^2 + 4x + 4 = 0").collect { response ->
    response.thoughtSummary?.let {
        if (thoughts.isEmpty()) {
            println("--- Thoughts Summary ---")
        }
        print(it)
        thoughts += it
    }
    response.text?.let {
        if (answer.isEmpty()) {
            println("--- Answer ---")
        }
        print(it)
        answer += it
    }
}

Java

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
ThinkingConfig thinkingConfig = new ThinkingConfig.Builder()
    .setIncludeThoughts(true)
    .build();

GenerationConfig generationConfig = GenerationConfig.builder()
    .setThinkingConfig(thinkingConfig)
    .build();

// Specify the config as part of creating the `GenerativeModel` instance
GenerativeModelFutures model = GenerativeModelFutures.from(
        FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel(
                  /* modelName */ "GEMINI_MODEL_NAME",
                  /* generationConfig */ generationConfig
                );
);

// Streaming with Java is complex and depends on the async library used.
// This is a conceptual example using a reactive stream.
Flowable responseStream = model.generateContentStream("solve x^2 + 4x + 4 = 0");

// Handle the streamed response that includes thought summaries
StringBuilder thoughts = new StringBuilder();
StringBuilder answer = new StringBuilder();

responseStream.subscribe(response -> {
    if (response.getThoughtSummary() != null) {
        if (thoughts.length() == 0) {
            System.out.println("--- Thoughts Summary ---");
        }
        System.out.print(response.getThoughtSummary());
        thoughts.append(response.getThoughtSummary());
    }
    if (response.getText() != null) {
        if (answer.length() == 0) {
            System.out.println("--- Answer ---");
        }
        System.out.print(response.getText());
        answer.append(response.getText());
    }
}, throwable -> {
    // Handle error
});

Web

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
const generationConfig = {
  thinkingConfig: {
    includeThoughts: true
  }
};

// Specify the config as part of creating the `GenerativeModel` instance
const model = getGenerativeModel(ai, { model: "GEMINI_MODEL_NAME", generationConfig });

const result = await model.generateContentStream("solve x^2 + 4x + 4 = 0");

// Handle the streamed response that includes thought summaries
let thoughts = "";
let answer = "";
for await (const chunk of result.stream) {
  if (chunk.thoughtSummary()) {
    if (thoughts === "") {
      console.log("--- Thoughts Summary ---");
    }
    // In Node.js, process.stdout.write(chunk.thoughtSummary()) could be used
    // to avoid extra newlines.
    console.log(chunk.thoughtSummary());
    thoughts += chunk.thoughtSummary();
  }

  const text = chunk.text();
  if (text) {
    if (answer === "") {
      console.log("--- Answer ---");
    }
    // In Node.js, process.stdout.write(text) could be used.
    console.log(text);
    answer += text;
  }
}

Dart

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
final thinkingConfig = ThinkingConfig(includeThoughts: true);

final generationConfig = GenerationConfig(
  thinkingConfig: thinkingConfig
);

// Specify the config as part of creating the `GenerativeModel` instance
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  generationConfig: generationConfig,
);

final responses = model.generateContentStream('solve x^2 + 4x + 4 = 0');

// Handle the streamed response that includes thought summaries
var thoughts = '';
var answer = '';
await for (final response in responses) {
  if (response.thoughtSummary != null) {
    if (thoughts.isEmpty) {
      print('--- Thoughts Summary ---');
    }
    thoughts += response.thoughtSummary!;
  }
  if (response.text != null) {
    if (answer.isEmpty) {
      print('--- Answer ---');
    }
    answer += response.text!;
  }
}

Unity

GenerativeModel 인스턴스를 만드는 과정에서 GenerationConfig에서 생각 요약을 사용 설정합니다.


// ...

// Set the thinking configuration
// Optionally enable thought summaries in the generated response (default is false)
var thinkingConfig = new ThinkingConfig(includeThoughts: true);

var generationConfig = new GenerationConfig(
  thinkingConfig: thinkingConfig
);

// Specify the config as part of creating the `GenerativeModel` instance
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  generationConfig: generationConfig
);

var stream = model.GenerateContentStreamAsync("solve x^2 + 4x + 4 = 0");

// Handle the streamed response that includes thought summaries
var thoughts = "";
var answer = "";
await foreach (var response in stream)
{
    if (response.ThoughtSummary != null)
    {
        if (string.IsNullOrEmpty(thoughts))
        {
            Debug.Log("--- Thoughts Summary ---");
        }
        Debug.Log(response.ThoughtSummary);
        thoughts += response.ThoughtSummary;
    }
    if (response.Text != null)
    {
        if (string.IsNullOrEmpty(answer))
        {
            Debug.Log("--- Answer ---");
        }
        Debug.Log(response.Text);
        answer += response.Text;
    }
}

사고 서명 이해하기

멀티턴 상호작용에서 사고를 사용하면 모델이 이전 턴의 사고 컨텍스트에 액세스할 수 없습니다. 하지만 함수 호출을 사용하는 경우 사고 서명을 활용하여 턴 전반에 걸쳐 사고 컨텍스트를 유지할 수 있습니다. 사고 서명은 모델의 내부 사고 프로세스를 암호화한 표현이며, 사고 함수 호출을 사용할 때 사용할 수 있습니다. 구체적으로 생각 서명은 다음과 같은 경우에 생성됩니다.

  • 사고가 사용 설정되어 있고 생각이 생성됩니다.
  • 요청에 함수 선언이 포함되어 있습니다.

생각 서명을 활용하려면 평소와 같이 함수 호출을 사용하세요. Firebase AI Logic SDK는 상태를 관리하고 생각 서명을 자동으로 처리하여 프로세스를 간소화합니다. SDK는 Chat 세션에서 후속 sendMessage 또는 sendMessageStream 호출 간에 생성된 생각 서명을 자동으로 전달합니다.

사고 토큰 가격 책정 및 집계

사고 토큰은 텍스트 출력 토큰과 동일한 가격을 사용합니다. 생각 요약을 사용 설정하면 생각 토큰으로 간주되어 그에 따라 가격이 책정됩니다.

Firebase 콘솔에서 AI 모니터링을 사용 설정하여 생각 기능이 사용 설정된 요청의 생각 토큰 수를 모니터링할 수 있습니다.

대답의 usageMetadata 속성에 있는 thoughtsTokenCount 필드에서 생각 토큰의 총수를 가져올 수 있습니다.

Swift

// ...

let response = try await model.generateContent("Why is the sky blue?")

if let usageMetadata = response.usageMetadata {
  print("Thoughts Token Count: \(usageMetadata.thoughtsTokenCount)")
}

Kotlin

// ...

val response = model.generateContent("Why is the sky blue?")

response.usageMetadata?.let { usageMetadata ->
    println("Thoughts Token Count: ${usageMetadata.thoughtsTokenCount}")
}

Java

// ...

ListenableFuture<GenerateContentResponse> response =
    model.generateContent("Why is the sky blue?");

Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String usageMetadata = result.getUsageMetadata();
        if (usageMetadata != null) {
            System.out.println("Thoughts Token Count: " +
                usageMetadata.getThoughtsTokenCount());
        }
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web

// ...

const response = await model.generateContent("Why is the sky blue?");

if (response?.usageMetadata?.thoughtsTokenCount != null) {
    console.log(`Thoughts Token Count: ${response.usageMetadata.thoughtsTokenCount}`);
}

Dart

// ...

final response = await model.generateContent(
  Content.text("Why is the sky blue?"),
]);

if (response?.usageMetadata case final usageMetadata?) {
  print("Thoughts Token Count: ${usageMetadata.thoughtsTokenCount}");
}

Unity

// ...

var response = await model.GenerateContentAsync("Why is the sky blue?");

if (response.UsageMetadata != null)
{
    UnityEngine.Debug.Log($"Thoughts Token Count: {response.UsageMetadata?.ThoughtsTokenCount}");
}

토큰 수 가이드에서 토큰에 대해 자세히 알아보세요.