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

설치와 클라이언트 설정

~10 min · python, google-genai, client

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

설치할 패키지는 google-genai야

공식 Python SDK는 google-genai야. pip 패키지 이름에는 하이픈을, import 경로에는 점을 써. 이 패키지는 2025년 11월에 수명 종료(EOL)된 google-generativeai를 대체해. 튜토리얼에서 import google.generativeai as genai를 쓴다면 수명 종료 이전 자료고, 지금은 API 구조가 달라졌어.

설치

기본 패키지에 더 빠른 비동기 처리를 위한 aiohttp 선택 옵션을 붙일 수 있어:

어디서나 쓰게 될 import 세 가지

  • from google import genai — 클라이언트를 만들어.
  • from google.genai import typesGenerateContentConfig, Tool, Part, HarmCategory 같은 설정 데이터 클래스를 제공해.
  • from google.genai import errorsAPIError, ClientError, ServerError 같은 예외 클래스를 제공해.

클라이언트를 만드는 세 가지 패턴

  1. 환경에서 자동 탐색genai.Client()GEMINI_API_KEYGOOGLE_API_KEY를 읽어.
  2. 키를 직접 지정genai.Client(api_key='...')를 써. 테스트하거나 여러 키를 다룰 때 유용해.
  3. Vertex AIgenai.Client(vertexai=True, project='...', location='...')를 써.

클라이언트 인스턴스 하나가 동기와 비동기 호출을 모두 맡아. 비동기 API는 client.aio.modelsclient.aio.chats 아래에 있어.

Code

설치·bash
pip install google-genai

# Optional: httpx 대신 aiohttp 통한 더 빠른 async
pip install 'google-genai[aiohttp]'
클라이언트 생성·python
from google import genai
from google.genai import types

# 1. env 의 GEMINI_API_KEY (또는 GOOGLE_API_KEY) 읽음 — 가장 흔함
client = genai.Client()

# 2. Explicit key
client = genai.Client(api_key='AIzaSy...')

# 3. Vertex AI
client = genai.Client(
    vertexai=True,
    project='my-project',
    location='us-central1',
)

# 4. 특정 API 버전 pin (default 는 v1beta)
client = genai.Client(
    http_options=types.HttpOptions(api_version='v1'),
)
동기와 비동기가 클라이언트 하나를 공유해·python
client = genai.Client()

# Sync
response = client.models.generate_content(
    model='gemini-2.5-flash', contents='Hi')
print(response.text)

# Async — 같은 client, .aio prefix
import asyncio

async def main():
    r = await client.aio.models.generate_content(
        model='gemini-2.5-flash', contents='Hi')
    print(r.text)

asyncio.run(main())

External links

Exercise

새 Python 환경을 만들고 google-genai[aiohttp]를 설치해. sync_hello()async_hello() 함수가 있는 스크립트를 작성하고, 각 함수에서 gemini-2.5-flashgenerate_content를 한 번 호출해 응답 텍스트를 출력해. 비동기 함수는 asyncio.run() 안에서 실행하고, 두 경로가 처음부터 끝까지 모두 작동하는지 확인해.

Progress

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

댓글 0

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

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