OpenAI SDK에서 생성형 AI SDK로 이전

이 페이지에서는 Vertex AI에서 Gemini 모델을 활용하기 위해 OpenAI SDK용으로 설계된 코드를 Google 생성형 AI SDK로 이전하는 방법을 설명합니다.

마이그레이션 개요

다음 노트북은 openai 라이브러리에서 google-genai 라이브러리로의 실제 마이그레이션을 보여줍니다.

API 및 구문 매핑

다음 표에서는 OpenAI SDK의 핵심 구성요소, 메서드, 매개변수를 생성형 AI SDK와 비교합니다.

기능 OpenAI SDK (openai) 생성형 AI SDK (google-genai)
클라이언트 초기화 client = OpenAI(api_key=...) client = genai.Client(vertexai=True, ...)
생성 방법 client.chat.completions.create client.models.generate_content
스트리밍 방법 stream=True (매개변수) client.models.generate_content_stream (메서드)
사용자 입력 messages=[{"role": "user", "content": "..."}] contents="..." (str) 또는 contents=[...] (list)
시스템 요청 사항 messages=[{"role": "system", "content": "..."}] config=types.GenerateContentConfig(system_instruction=...)
응답 액세스 response.choices[0].message.content response.text
채팅기록 수동 목록 관리 (messages.append) client.chats.create() (스테이트풀 객체)
최대 토큰 수 max_tokens max_output_tokens (config 내부)
온도 temperature temperature (config 내부)
JSON 모드 response_format={"type": "json_object"} response_mime_type="application/json" (config 내부)

설치 및 설정

OpenAI 라이브러리를 제거하고 생성형 AI SDK를 설치합니다.

pip install google-genai

2. 인증 및 초기화

OpenAI는 API 키를 사용하는 반면 Vertex AI는 Identity and Access Management (IAM) 사용자 인증 정보 (애플리케이션 기본 사용자 인증 정보)를 사용합니다. 프로젝트 ID와 위치를 명시적으로 정의해야 합니다.

OpenAI SDK Google Gen AI SDK
from openai import OpenAI
import os

# Relies on OPENAI_API_KEY environment variable
client = OpenAI()
        
from google import genai

# Use vertexai=True to use the Vertex AI platform
client = genai.Client(
    vertexai=True,
    project='your-project-id',
    location='us-central1'
)
        
도움말: OpenAI 클라이언트가 환경에서 API 키를 읽는 방식과 유사하게 환경 변수를 설정하여 인수 없이 클라이언트를 초기화할 수도 있습니다.

다음과 같이 GOOGLE_GENAI_USE_VERTEXAI, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION를 설정합니다.

export GOOGLE_GENAI_USE_VERTEXAI=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='global'

구성한 후 매개변수를 전달하지 않고 클라이언트를 초기화할 수 있습니다.

from google import genai

client = genai.Client()

코드 예시

다음 코드 샘플은 일반적인 작업에 대한 OpenAI SDK와 Google Gen AI SDK의 차이점을 보여줍니다.

싱글턴 텍스트 생성

다음 코드 샘플은 텍스트를 생성하는 방법을 보여줍니다. Google Gen AI SDK에서는 시스템 명령어가 입력 목록의 메시지 역할이 아닌 구성 매개변수로 처리됩니다.

OpenAI SDK Google Gen AI SDK
response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain quantum physics."}
    ]
)
print(response.choices[0].message.content)
        
from google.genai import types

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Explain quantum physics.",
    config=types.GenerateContentConfig(
        system_instruction="You are a helpful assistant."
    )
)
print(response.text)
        

매개변수를 사용하여 텍스트 생성

다음 코드 샘플은 구성 매개변수 정의의 차이점을 보여줍니다. Google 생성형 AI SDK에서 temperature, max_output_tokens (이전 max_tokens), JSON 형식과 같은 매개변수는 GenerateContentConfig 객체로 그룹화됩니다.

OpenAI SDK Google Gen AI SDK
response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "user", "content": "List 3 types of apples in JSON."}
    ],
    temperature=0.7,
    max_tokens=1000,
    response_format={"type": "json_object"}
)

print(response.choices[0].message.content)
        
from google.genai import types

config = types.GenerateContentConfig(
    temperature=0.7,
    max_output_tokens=1000,
    response_mime_type="application/json"
)

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="List 3 types of apples in JSON.",
    config=config
)

print(response.text)
        

채팅 (멀티턴)

다음 코드 샘플은 채팅 기록 관리의 차이점을 보여줍니다. Google Gen AI SDK는 상태 저장 chat 객체를 제공하여 이를 간소화하는 반면 OpenAI에서는 목록에 메시지를 수동으로 추가해야 합니다.

OpenAI SDK Google Gen AI SDK
# You must manually manage the list state
messages = [{"role": "user", "content": "Hi"}]

response = client.chat.completions.create(
    model="gpt-4",
    messages=messages
)

# Append the response to history manually
messages.append(response.choices[0].message)
messages.append({"role": "user", "content": "Next question"})

response2 = client.chat.completions.create(
    model="gpt-4",
    messages=messages
)
print(response2.choices[0].message.content)
        
# The SDK manages history for you
chat = client.chats.create(
    model="gemini-2.5-flash",
    config=types.GenerateContentConfig(
        system_instruction="You are a helpful assistant."
    )
)

response1 = chat.send_message("Hi")
print(response1.text)

# History is retained automatically in the chat object
response2 = chat.send_message("Next question")
print(response2.text)
        

스트리밍

다음 코드 샘플은 스트리밍 응답의 차이점을 보여줍니다. Google 생성형 AI SDK는 불리언 플래그가 아닌 특정 메서드 (generate_content_stream)를 사용합니다.

OpenAI SDK Google Gen AI SDK
stream = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Write a story."}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
        
stream = client.models.generate_content_stream(
    model="gemini-2.5-flash",
    contents="Write a story."
)

for chunk in stream:
    print(chunk.text, end="")
        

다음 단계