C.W.K.
Stream
Lesson 03 of 07 · published

Chat Completions — sync 호출과 multi-turn

~22 min · chat-completions, sync, messages

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

Chat Completions 는 stateless 야. 매 turn 마다 전체 message list 를 다시 보내. 한 번 빼먹으면 모델은 그 turn 의 대화를 잊어버려.

History trim 은 turn 이 아니라 token 으로

'마지막 10 메시지 유지' 같은 turn-based 윈도잉은 메시지 하나가 거대해지면 깨져. Token budget 으로 trim — tiktoken 으로 토큰 세고, system 메시지는 보존, 오래된 non-system 메시지부터 drop.

Skeleton 외워두면 빨라져

모든 호출의 필수 인자 셋 — model, messages, (Responses-class 모델은) max_completion_tokens. 매 응답의 필드 — id, choices, usage, created. 이 skeleton 외우면 docs 매번 안 봐도 돼.

Conversational ergonomics 의 함정

API 가 stateless 라서 chat UI 빌드는 dev 의 책임. 가장 흔한 버그 — 메시지 배열을 끝없이 키워. 3 주 차에 매 request 가 50 토큰 user message 에 20K 토큰 history 를 같이 보냄. 아래 exercise 가 canonical fix.

Code

Single-turn completion·python
from openai import OpenAI

client = OpenAI()

completion = client.chat.completions.create(
    model="gpt-5.4",
    messages=[
        {"role": "developer", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain black holes in one paragraph."},
    ],
    temperature=0.5,
    max_completion_tokens=300,
    reasoning_effort="low",
)

# Access the response
text = completion.choices[0].message.content
usage = completion.usage  # .prompt_tokens, .completion_tokens, .total_tokens
print(text)
print(f"Used {usage.total_tokens} tokens")
Multi-turn with explicit history·python
import asyncio
from openai import AsyncOpenAI

async_client = AsyncOpenAI()

async def get_completion():
    completion = await async_client.chat.completions.create(
        model="gpt-5.4",
        messages=[{"role": "user", "content": "Hello!"}],
    )
    return completion.choices[0].message.content

result = asyncio.run(get_completion())

External links

Exercise

대화 history 유지하는 작은 REPL 만들어. Total input token 이 8K 넘지 않도록 trim 추가 — system 메시지 보존, 가장 오래된 non-system 메시지부터 drop.

Progress

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

댓글 0

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

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