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

Chat Completions API

~22 min · chat-completions, messages, roles

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

Chat Completions API 는 OpenAI 언어 모델과 대화하는 가장 기본적인 창구야. 호출할 때는 role 이 붙은 messages 목록을 보내고, 모델이 만든 completion 을 응답으로 받아.

요청의 중심은 message 배열이야. 각 message 에는 rolecontent 가 들어가. role 은 이렇게 나뉘어:

  • system / developer — 모델이 따라야 할 상위 지시야. GPT-5.x 부터는 developer 가 권장돼.
  • user — 실제 사용자가 보낸 메시지야.
  • assistant — 모델이 앞선 turn 에서 보낸 응답이야. 여러 turn 을 이어갈 때 넣어.
  • tool — 도구나 function call 의 실행 결과야. tool_call_id 로 원래 호출과 연결해.

요청부터 응답까지

POST 요청을 보내고 HTTP 200 응답을 받으면, choices 에서 텍스트를 꺼내고 usage 에서 사용한 token 수를 확인해. stream: true 를 넣으면 한 번에 완성된 응답을 받는 대신 SSE(Server-Sent Events) chunk 가 차례로 도착해.

응답에서 꼭 볼 필드

응답에는 보통 원소 하나를 담은 choices 배열이 있어. 각 원소에는 messagefinish_reason 이 들어가. stop 은 자연스럽게 끝났다는 뜻이고, length 는 token 한도에 걸려 잘렸다는 뜻이야. tool_calls 는 도구를 호출하려는 응답, content_filter 는 안전 필터에 막힌 응답을 가리켜. 정확한 token 사용량은 usage 에서 확인해.

finish_reason 을 빼먹으면 생기는 일

finish_reason 을 읽지 않으면 token 한도 때문에 잘린 응답이나 도구를 호출하려는 응답을 정상적인 최종 답변으로 착각할 수 있어. 개발 중에는 운 좋게 안 보이다가 운영 환경에서 터지는 단골 버그야. 호출할 때마다 확인해.

Code

Request shape (HTTP)·text
Client → POST /v1/chat/completions (messages[], model, params)
       ← HTTP 200 { id, object, created, model, choices[], usage }
Streaming SSE shape·text
Client → POST /v1/chat/completions (stream: true)
       ← HTTP 200 text/event-stream
         data: {"id":"...","choices":[{"delta":{"content":"..."}}]}
         data: [DONE]
Minimal Python 예제·python
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from env

completion = client.chat.completions.create(
    model="gpt-5.4",
    messages=[
        {"role": "developer", "content": "You are a concise assistant."},
        {"role": "user", "content": "What is the speed of light?"},
    ],
    temperature=0.7,
    max_completion_tokens=200,
)

print(completion.choices[0].message.content)
print(f"Tokens used: {completion.usage.total_tokens}")
print(f"Finish reason: {completion.choices[0].finish_reason}")

External links

Exercise

developer 와 user 메시지를 함께 넣어 chat completion 을 보내고, assistant 텍스트와 finish_reason, 전체 token 수를 출력해. 이어서 max_completion_tokens 를 5 로 줄여 다시 호출한 뒤 finish_reason 이 'length' 로 바뀌는지 확인해.

Progress

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

댓글 0

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

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