토큰 사용량
토큰 사용량 (Usage)
LLM 응답에서 '얼마나 많은 토큰을 썼는지'는 비용과 한도 관리의 핵심 정보예요. LiteLLM은 모든 프로바이더에서 OpenAI 호환 usage 객체를 그대로 돌려줘서, 어느 모델을 쓰든 같은 형태로 토큰 수를 읽을 수 있게 해 줘요. 비용 추정과 스트리밍 토큰 집계까지, 사용량을 다루는 방법을 살펴볼게요.
출처: 공식문서 Usage
OpenAI 호환 usage 객체
LiteLLM은 프로바이더가 달라도 usage 필드를 OpenAI 형식으로 통일해 반환해요.
"usage": {
"prompt_tokens": int,
"completion_tokens": int,
"total_tokens": int
}
퀵스타트
키를 환경변수로 설정하고 completion()을 호출하면 response.usage로 토큰 수를 읽을 수 있어요.
from litellm import completion
import os
# set ENV variables
os.environ["OPENAI_API_KEY"] = "your-api-key"
response = completion(
model="gpt-3.5-turbo",
messages=[{ "content": "Hello, how are you?", "role": "user"}]
)
print(response.usage)
참고: LiteLLM은 엔드포인트 브리징을 지원해요. 요청한 엔드포인트를 모델이 네이티브로 지원하지 않으면,
model_prices_and_context_window에 정의된 모델의mode에 따라 자동으로 올바른 엔드포인트(예:/chat/completions↔/responses)로 라우팅해요.
스트리밍 사용량
stream_options={"include_usage": True}를 설정하면 data: [DONE] 메시지 전에 추가 청크 하나가 스트리밍돼요. 이 청크의 usage 필드는 전체 요청의 토큰 통계를 담고, choices 필드는 항상 빈 배열이에요. 나머지 청크에도 usage 필드는 있지만 null 값이에요.
from litellm import completion
completion = completion(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
stream=True,
stream_options={"include_usage": True}
)
for chunk in completion:
print(chunk.choices[0].delta)
프록시: 스트리밍 사용량 항상 포함하기
게이트웨이를 쓴다면 클라이언트가 stream_options={"include_usage": True}를 보내지 않아도 모든 스트리밍 응답에 사용량을 자동 포함시킬 수 있어요.
설정
config.yaml에 다음을 추가해요.
general_settings:
always_include_stream_usage: true
UI로도 설정할 수 있어요.
- LiteLLM Proxy UI 열기
Settings>Router Settings>General이동always_include_stream_usage설정 찾기true로 토글Update클릭해 저장
동작 방식
always_include_stream_usage가 켜지면:
- 모든 스트리밍 요청에
stream_options={"include_usage": True}가 자동 추가돼요. - 클라이언트가 명시적으로 요청하지 않아도 마지막 청크에서 사용량을 받아요.
- 클라이언트가 이미
stream_options를 보냈다면include_usage: True가 다른 옵션을 덮지 않고 추가돼요. - 비스트리밍 요청은 영향받지 않아요.
예시
이 설정이 켜져 있으면, 아래처럼 stream_options 없이 보낸 단순 스트리밍 요청도 응답에 사용량 정보를 자동으로 받을 수 있어요.
curl -X POST http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer sk-1234" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Hello!"}],
"stream": true
}'
핵심 포인트
- usage 객체는 모든 프로바이더에서 OpenAI 호환 포맷으로 통일돼요.
- 스트리밍 사용량을 보려면
stream_options={"include_usage": True}를 켜야 해요. - 게이트웨이에선
always_include_stream_usage로 클라이언트 작업 없이 항상 포함시킬 수 있어요.