2026.09.18Backend · LLM
FastAPI로 LLM 응답 스트리밍하기
[도입 2–3문장 — 스트리밍이 필요했던 상황과 이 글의 범위]
- Published
- 2026.09.18
- Reading
- 1 min
- Tags
- FastAPIStreamingLLM
01들어가며
To write — 배경응답 대기 시간이 문제가 됐던 구체적인 장면.
02구현
StreamingResponse에 비동기 제너레이터를 넘기면 토큰이 생성되는 대로 응답을 보낼 수 있습니다.
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.get("/chat")
async def chat(q: str):
async def tokens():
async for chunk in llm.astream(q):
yield chunk
return StreamingResponse(tokens(), media_type="text/plain")03정리
Lessons프록시·타임아웃 등 배포 환경에서 확인할 것.