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

채팅과 오류 처리

~14 min · chat, history, errors, retry

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

20줄을 덜어 주는 채팅

client.chats.create()는 대화 기록을 유지하는 채팅 세션을 반환해. send_message를 호출할 때마다 사용자 차례를 덧붙이고, 전체 기록으로 generate_content를 호출한 뒤 모델 답변도 덧붙여. 직접 20줄쯤 써서 같은 기능을 만들 수 있지만, 이 래퍼는 그 코드와 "모델 차례를 기록하는 걸 깜빡하는" 버그를 함께 없애 줘.

스트리밍 채팅도 있어

chat.send_message_stream(...)이 스트리밍 버전이야. 이터레이터 구조는 generate_content_stream과 같아.

디버깅할 때 대화 기록 살펴보기

chat.get_history()는 전체 대화를 list[Content]로 반환해. 출력하거나 저장하거나 이전 상태로 되돌릴 때 유용해.

오류는 세 단계의 클래스 계층으로 나뉘어

  • errors.APIError — 기반 클래스야. 하위 클래스를 구분할 필요가 없다면 이것을 잡아.
  • errors.ClientError — 400, 401, 403, 404, 429 같은 4xx 오류야. 잘못된 요청·인증·호출 한도처럼 호출하는 쪽에서 고쳐야 해.
  • errors.ServerError — 500, 503 같은 5xx 오류야. 서버 쪽 문제이므로 지수 백오프로 다시 시도해.

HTTP 상태 코드는 e.code, 사람이 읽을 메시지는 e.message에 있어.

Code

여러 차례 이어지는 채팅·python
chat = client.chats.create(
    model='gemini-2.5-flash',
    config=types.GenerateContentConfig(
        system_instruction='You are a precise but warm tutor.',
    ),
)

r1 = chat.send_message('Tell me a fact about octopuses.')
print('AI:', r1.text)

r2 = chat.send_message('Now relate that fact to neural networks.')
print('AI:', r2.text)

# History 검사
for msg in chat.get_history():
    role = msg.role
    text = msg.parts[0].text if msg.parts and hasattr(msg.parts[0], 'text') else '<non-text>'
    print(f'{role}: {text[:80]}...')
스트리밍 채팅·python
chat = client.chats.create(model='gemini-2.5-flash')

for chunk in chat.send_message_stream('Write me a haiku about debugging.'):
    if chunk.text:
        print(chunk.text, end='', flush=True)
print()
복원력 있는 오류 처리·python
import time
from google.genai import errors

def robust_generate(client, model, contents, max_retries=4):
    for attempt in range(max_retries):
        try:
            return client.models.generate_content(
                model=model, contents=contents)
        except errors.ClientError as e:
            if e.code == 429:
                # Rate limit — exponential backoff
                sleep = min(2 ** attempt, 30)
                print(f'429 — sleeping {sleep}s')
                time.sleep(sleep)
                continue
            # 400/401/403/404 는 transient 아님 — re-raise
            raise
        except errors.ServerError as e:
            # 5xx — backoff 으로 retry
            time.sleep(min(2 ** attempt, 30))
            continue
    raise RuntimeError(f'Gave up after {max_retries} retries')

External links

Exercise

채팅 반복 CLI를 만들어. 표준 입력에서 한 줄씩 읽어 chat.send_message_stream으로 보내고, 응답은 표준 출력으로 스트리밍해. 매 차례가 끝나면 전체 기록을 chat.jsonl에 저장해. 모든 API 호출에 위 robust_generate 패턴을 적용해 429가 세션을 죽이지 않게 하고, 시작할 때 JSONL을 다시 읽어 프로그램을 재시작해도 대화가 이어지는지 확인해.

Progress

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

댓글 0

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

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