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

Client 초기화 — 1 process 당 1 client

~22 min · client, async, httpx

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

SDK 는 동기식 OpenAI() 와 비동기식 AsyncOpenAI() client 를 제공해. 둘 다 내부의 httpx connection pool 을 재사용하도록 만들어졌어. app 이 시작할 때 process 마다 하나를 만들고 종료할 때까지 함께 써. 호출할 때마다 새 client 를 만드는 건 눈에 잘 띄지 않는 성능 버그야.

왜 process 마다 하나일까?

OpenAI() 를 새로 만들 때마다 httpx client 와 connection pool 도 새로 생겨. 요청마다 만들고 버리면 TLS handshake 를 계속 되풀이하고 keep-alive 와 pooling 의 이점을 잃어. 부하가 늘면 긴 꼬리 지연과 connection 한도 경고로 나타나.

async framework 에서는 AsyncOpenAI

sync client 는 event loop 를 막아. FastAPI, Starlette, aiohttp 안에서는 AsyncOpenAI() 를 사용해. async handler 에 sync 호출을 섞으면 서버 전체가 느려질 수 있어.

한 호출만 설정을 바꾸는 법

특정 호출에만 다른 timeout 이나 재시도 횟수가 필요하다면 client.with_options(max_retries=5, timeout=120.0).chat.completions.create(...) 를 써. connection pool 은 그대로 재사용하면서 그 호출의 설정만 바꿀 수 있어.

Code

Sync OpenAI() client·python
from openai import OpenAI

# Minimal — reads OPENAI_API_KEY automatically
client = OpenAI()

# Full configuration
client = OpenAI(
    api_key=os.environ["OPENAI_API_KEY"],
    organization="org-XXXXXXXXXXXXXXXX",
    project="proj_XXXXXXXXXXXXXXXX",
    timeout=60.0,       # default is 600s (10 min)
    max_retries=2,      # default is 2
    base_url="https://api.openai.com/v1",  # override for proxies
)
AsyncOpenAI() with custom timeout·python
from openai import AsyncOpenAI

async_client = AsyncOpenAI(
    api_key=os.environ["OPENAI_API_KEY"],
)

# Use in async context
async def main():
    response = await async_client.responses.create(
        model="gpt-5.4",
        input="Hello!",
    )
    print(response.output_text)

External links

Exercise

AsyncOpenAI 를 사용하는 GET /chat endpoint 하나짜리 작은 FastAPI 앱을 만들어. Apache Bench 또는 hey 로 동시 요청 100 건을 보내 서로를 막지 않는지 확인해.

Progress

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

댓글 0

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

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