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

Response 구조 — choices, usage, tool_calls

~22 min · response, choices, usage

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

응답 텍스트는 completion.choices[0].message.content 에 있어. completion.message 로 바로 접근할 수는 없어. choices 는 원소가 하나뿐이어도 배열이고, n>1 을 허용하는 공용 코드라면 모든 원소를 순회해야 해.

usage 는 비용을 설명하는 기록이야

요청마다 usage.prompt_tokens, completion_tokens, total_tokens 를 request ID 와 함께 저장해. 나중에 청구액이 예상과 다를 때 어떤 호출이 비용을 만들었는지 추적할 근거가 돼.

tool_calls 는 없을 수도 있어

도구를 호출하지 않은 turn 에서는 completion.choices[0].message.tool_calls 가 None 일 수 있어. getattr(msg, 'tool_calls', None) or [] 처럼 값이 없을 때 빈 배열로 다루는 방식이 안전해.

공통으로 풀어주는 helper 를 만들어

응답을 {text, finish_reason, prompt_tokens, completion_tokens, tool_calls?} 형태로 바꾸는 null-safe helper 하나를 두면 모든 호출부가 같은 구조를 쓸 수 있어. 로그를 남기기도 훨씬 쉬워져.

Code

Choices 와 usage 검사·json
{
  "id": "chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT",
  "object": "chat.completion",
  "created": 1741569952,
  "model": "gpt-4.1-2025-04-14",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Hello! How can I assist you today?",
      "refusal": null,
      "annotations": [],
      "tool_calls": null
    },
    "logprobs": null,
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 19,
    "completion_tokens": 10,
    "total_tokens": 29,
    "prompt_tokens_details": { "cached_tokens": 0 },
    "completion_tokens_details": { "reasoning_tokens": 0 }
  }
}

External links

Exercise

completion 을 받아 {text, finish_reason, prompt_tokens, completion_tokens, tool_calls?} dict 를 반환하는 unwrap_completion(c) helper 를 작성해. 모든 필드는 null-safe 하게 처리하고 코드 세 곳에서 사용해봐.

Progress

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

댓글 0

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

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