LiteLLM의 심장은 completion() 함수 하나다. model과 messages만 주면, 어떤 공급자든 OpenAI Chat Completions 포맷으로 응답을 돌려준다. 응답 접근 방식이 항상 같으므로 공급자를 바꿔도 파싱 코드를 고칠 필요가 없다.
이 강의 목표는 messages 구조, 응답 객체(ModelResponse)에서 텍스트·토큰을 꺼내는 법, 자주 쓰는 파라미터를 익히는 것이다.
1. messages 구조
messages는 역할과 내용의 리스트다. 역할은 system(지시)·user(사용자)·assistant(모델 답변) 세 가지가 기본이다.
messages = [
{"role": "system", "content": "너는 간결한 한국어 조수야."},
{"role": "user", "content": "LiteLLM의 장점 세 가지만."},
]
2. 응답 객체에서 값 꺼내기
응답은 ModelResponse 객체이며 OpenAI와 동일하게 접근한다.
from litellm import completion
resp = completion(model="openai/gpt-4o", messages=messages,
temperature=0.7, max_tokens=300)
print(resp.choices[0].message.content) # 답변 텍스트
print(resp.choices[0].finish_reason) # 종료 사유(stop 등)
print(resp.usage.prompt_tokens) # 입력 토큰
print(resp.usage.completion_tokens) # 출력 토큰
print(resp.usage.total_tokens) # 합계
3. 자주 쓰는 파라미터
temperature: 창의성(0=결정적 ~ 2=자유분방).max_tokens: 출력 토큰 상한.top_p,stop,response_format={"type":"json_object"}(JSON 강제).
핵심 명령·용어
| 이름 | 뜻 |
|---|---|
messages |
role/content 리스트(대화 이력) |
resp.choices[0].message.content |
답변 텍스트 |
resp.usage.total_tokens |
사용 토큰 수 |
finish_reason |
응답 종료 사유 |
예제
resp = completion(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "숫자 3개를 JSON 배열로만 답해"}],
response_format={"type": "json_object"},
)
print(resp.choices[0].message.content) # {"numbers":[1,2,3]}
해설) response_format으로 JSON 출력을 강제하면 후처리가 쉽다. 이 옵션도 공급자와 무관하게 동일한 방식으로 동작한다.
댓글 0
댓글은 운영자만 작성할 수 있어요.