본문 바로가기
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 API 야. turn 마다 전체 message 목록을 다시 보내야 해. 하나라도 빠뜨리면 모델은 그 부분의 대화를 알 수 없어.

history 는 turn 수가 아니라 token 수로 줄여

'마지막 메시지 열 개 유지' 같은 방식은 메시지 하나가 아주 길어지면 무너져. tiktoken 으로 token 수를 재고, system 메시지는 보존하면서 오래된 non-system 메시지부터 제거해 정한 예산 안에 맞춰.

기본 요청과 응답 구조를 익혀둬

호출할 때는 model, messages, Responses 계열 모델이라면 max_completion_tokens 를 자주 쓰게 돼. 응답에서는 id, choices, usage, created 를 확인해. 이 뼈대를 익히면 매번 문서를 처음부터 찾지 않아도 돼.

끝없이 자라는 대화 기록을 막아

stateless API 위에서 대화 기록을 관리하는 건 개발자의 책임이야. 메시지 배열을 계속 키우면 짧은 user message 하나를 보낼 때도 수만 token 의 history 를 매번 함께 보내게 돼. 아래 연습에서 token 예산으로 자르는 방식을 구현해봐.

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 을 만들어. 전체 input 이 8K token 을 넘지 않도록 system 메시지는 보존하고, 가장 오래된 non-system 메시지부터 제거해.

Progress

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

댓글 0

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

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