본문 바로가기
C.W.K.
Stream
Lesson 02 of 05 · published

generate_content()와 응답 구조

~14 min · python, generation, response, config

Level 0불씨
0 XP0/35 lessons0/10 achievements
0/140 XP to next level140 XP to go0% complete

10,000번 쓰게 될 호출 하나

client.models.generate_content(model=..., contents=..., config=...)가 SDK의 심장이야. contents에는 일반 문자열, 문자열 목록, Content 객체 목록 등 여러 형태를 넣을 수 있어. SDK가 알맞은 구조로 정규화해 줘.

GenerateContentConfig로 설정하기

앞 레슨에서 본 system_instruction, temperature, max_output_tokens 같은 모든 조절값은 types.GenerateContentConfig에 들어가. 일반 dict를 전달해도 SDK가 변환해 줘.

응답 객체 들여다보기

반환값은 GenerateContentResponse야. 가장 자주 쓰는 필드는 다음과 같아:

  • response.text — 모든 part의 텍스트를 합친 값이야. 90%의 경우 이것만 쓰면 돼.
  • response.parts — 가공하지 않은 목록이야. 이미지나 함수 호출 같은 비텍스트 part가 필요할 때 써.
  • response.function_calls — 모델이 도구를 호출했을 때 채워져.
  • response.parsed — Pydantic 스키마로 JSON 모드를 썼을 때 역직렬화된 객체야.
  • response.candidates[0].finish_reason — 생성이 멈춘 이유야.
  • response.usage_metadata — 과금에 필요한 토큰 수야.

가장 먼저 확인할 값

Gemini 응답을 받은 처리기의 첫 줄에서는 finish_reason을 봐야 해. STOP이 아니라면 response.text를 믿지 마. 필터에 걸려 비어 있을 수도 있고, 최대 토큰에 닿아 잘렸을 수도 있고, 학습 데이터 반복으로 차단됐을 수도 있어.

Code

일반 텍스트를 넣고 텍스트 받기·python
from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents='Why is the sky blue?',
)
print(response.text)
설정과 함께 호출하기·python
response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents='Explain quantum entanglement to a curious 10-year-old.',
    config=types.GenerateContentConfig(
        system_instruction='You are a warm, accurate physics tutor.',
        max_output_tokens=400,
        temperature=0.5,
        top_p=0.95,
        top_k=40,
        seed=42,
    ),
)

# Config 는 dict 도 가능 — SDK 가 변환
response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents='Hello',
    config={'temperature': 0.0, 'max_output_tokens': 50},
)
응답을 올바르게 읽기·python
candidate = response.candidates[0]
reason = candidate.finish_reason

if reason.name != 'STOP':
    # MAX_TOKENS, SAFETY, RECITATION, OTHER
    raise RuntimeError(f'Generation did not finish cleanly: {reason.name}')

text = response.text
usage = response.usage_metadata

print(f'Reply ({usage.total_token_count} tokens):')
print(text)
print(f'  prompt={usage.prompt_token_count}  '
      f'completion={usage.candidates_token_count}')

External links

Exercise

작은 safe_generate(prompt: str) -> str 도우미를 작성해. (1) Flash를 200토큰 상한으로 generate_content 호출하고, (2) finish_reason을 확인해 STOP이 아니면 사용자 정의 GenerationError를 일으키고, (3) 성공하면 텍스트를 반환해야 해. 평범한 프롬프트, 작은 상한으로 MAX_TOKENS를 일으키는 프롬프트, 안전 분류기가 거를 만한 프롬프트로 세 분기를 검증해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.