응답을 통째로 기다리면 사용자 체감이 느리다. 스트리밍은 토큰이 생성되는 즉시 흘려보내 첫 글자가 빨리 뜨게 한다. 비동기(acompletion)는 여러 호출을 동시에 처리해 처리량을 높인다. 둘 다 completion()과 같은 인자를 쓴다.
이 강의 목표는 스트리밍으로 실시간 출력을 만들고, asyncio로 다수 요청을 병렬 처리하는 것이다.
1. 스트리밍
stream=True를 주면 응답이 청크(chunk) 제너레이터로 온다. 텍스트는 delta.content에 조금씩 담긴다.
from litellm import completion
stream = completion(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "짧은 시 한 편"}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="", flush=True)
마지막 청크의 delta.content는 None이 될 수 있어 or ""로 방어한다. 사용량까지 받으려면 stream_options={"include_usage": True}를 준다.
2. 비동기
acompletion은 코루틴이다. asyncio.gather로 여러 요청을 병렬 실행한다.
import asyncio
from litellm import acompletion
async def ask(q):
r = await acompletion(model="openai/gpt-4o",
messages=[{"role": "user", "content": q}])
return r.choices[0].message.content
async def main():
qs = ["파이썬이란?", "비동기란?", "코루틴이란?"]
answers = await asyncio.gather(*[ask(q) for q in qs])
for a in answers:
print(a[:40])
asyncio.run(main())
핵심 명령·용어
| 이름 | 뜻 |
|---|---|
stream=True |
토큰 실시간 스트리밍 |
chunk.choices[0].delta.content |
청크 조각 텍스트 |
acompletion() |
비동기 호출(await) |
asyncio.gather |
다수 코루틴 병렬 실행 |
예제
# 스트리밍 비동기: astream
async def stream_it():
s = await acompletion(model="openai/gpt-4o",
messages=[{"role":"user","content":"카운트 1~5"}],
stream=True)
async for chunk in s:
print(chunk.choices[0].delta.content or "", end="")
해설) 비동기 스트리밍은 async for로 청크를 받는다. 웹 서버(FastAPI 등)에서 SSE로 흘려보낼 때 이 패턴을 쓴다.
댓글 0
댓글은 운영자만 작성할 수 있어요.