본문으로 건너뛰기
cabby

FastAPI

FastAPI가 StreamingResponse로 AI 응답을 바로 흘려보내면 신호가 끊기거나 페이지를 새로고침할 때 스트림이 중간에 끊어집니다. 대신 Cabby를 앞단에 두세요. FastAPI는 BackgroundTasks에서 생성을 실행해 각 청크를 httpx로 HTTP 전송하고, Cabby는 Server-Sent Events 연결을 유지하면서 스트림 기록을 SQLite에 보관합니다. 클라이언트가 다시 연결하거나 새로고침해도 놓친 청크를 모두 이어받을 수 있으며 Redis는 필요하지 않습니다.

1. Cabby 실행하기

Cabby를 설치한 뒤 SSE와 SQLite 브로커를 켜고 독립 실행 모드로 시작하세요.

cabby --norpc --noauth --sse --secret=change-me --broadcast_key=change-me-too \
  --broadcast_adapter=http --broker=sqlite --sqlite_path=./cabby.db \
  --allowed_origins=localhost:8000
  • --norpc와 --noauth는 Cabby를 독립 실행 모드로 띄웁니다. 각 방문자가 읽을 수 있는 스트림은 서명된 스트림 이름이 결정합니다.
  • --sse는 /events 경로에 Server-Sent Events 엔드포인트를 켭니다.
  • --broker=sqlite와 --sqlite_path=./cabby.db는 최근 스트림 기록을 로컬 파일 하나에 저장합니다. 기본값은 스트림당 최근 100개 메시지를 5분간 보관하며, 긴 응답은 --history_limit과 --history_ttl로 늘릴 수 있습니다(설정).
  • --allowed_origins는 브라우저 연결을 FastAPI 앱이 제공하는 페이지로 제한합니다. 값은 페이지의 호스트와 포트이며 http://는 붙이지 않습니다.

2. 작은 헬퍼 모듈 추가하기

FastAPI, Uvicorn, httpx를 설치하세요.

pip install fastapi uvicorn httpx

스트림 이름에 서명하고 비동기로 브로드캐스트하는 cabby.py를 추가합니다. CABBY_SECRET과 CABBY_BROADCAST_KEY는 --secret 및 --broadcast_key와 같은 값을 쓰고, CABBY_BROADCAST_URL은 Cabby의 HTTP 브로드캐스트 엔드포인트를 가리킵니다.

# cabby.py
import base64
import hashlib
import hmac
import json
import os

import httpx

CABBY_SECRET = os.environ.get("CABBY_SECRET", "change-me")
CABBY_BROADCAST_KEY = os.environ.get("CABBY_BROADCAST_KEY", "change-me-too")
CABBY_BROADCAST_URL = os.environ.get("CABBY_BROADCAST_URL", "http://localhost:8080/_broadcast")

client = httpx.AsyncClient(timeout=5.0)


def sign_stream(name: str) -> str:
    encoded = base64.b64encode(json.dumps(name).encode()).decode()
    digest = hmac.new(CABBY_SECRET.encode(), encoded.encode(), hashlib.sha256).hexdigest()
    return f"{encoded}--{digest}"


async def broadcast(stream: str, data: dict) -> None:
    response = await client.post(
        CABBY_BROADCAST_URL,
        json={"stream": stream, "data": json.dumps(data)},
        headers={"Authorization": f"Bearer {CABBY_BROADCAST_KEY}"},
    )
    response.raise_for_status()

3. 백그라운드 태스크에서 스트리밍하기

main.py의 POST /runs는 BackgroundTasks로 생성 작업을 시작하고 서명된 스트림 이름과 시작 시각을 바로 돌려줍니다. 방문자가 탭을 닫거나 연결이 끊겨도 생성은 끝까지 이어집니다.

# main.py
import asyncio
import time
import uuid
from contextlib import asynccontextmanager

from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel

from cabby import broadcast, client, sign_stream


@asynccontextmanager
async def lifespan(_app: FastAPI):
    yield
    await client.aclose()


app = FastAPI(lifespan=lifespan)


class PromptRequest(BaseModel):
    prompt: str


async def generate_reply(stream: str, prompt: str) -> None:
    # Replace this loop with your model SDK's async token stream.
    words = f"Streaming a reply for: {prompt}".split()
    for index, word in enumerate(words):
        prefix = "" if index == 0 else " "
        await broadcast(stream, {"delta": f"{prefix}{word}"})
        await asyncio.sleep(0.15)
    await broadcast(stream, {"done": True})


@app.post("/runs")
async def create_run(body: PromptRequest, tasks: BackgroundTasks):
    run_id = uuid.uuid4().hex
    stream = f"runs/{run_id}"
    started_at = int(time.time())
    tasks.add_task(generate_reply, stream, body.prompt)
    return {
        "run_id": run_id,
        "signed_stream": sign_stream(stream),
        "started_at": started_at,
    }

4. 브라우저에서 구독하고 이어받기

브라우저에 내장된 EventSource로 연결합니다. 별도 클라이언트 패키지가 필요하지 않습니다.

const params = new URLSearchParams({
  signed_stream: signedStream,
  raw: "true",
  history_since: String(startedAt),
})

const events = new EventSource(`http://localhost:8080/events?${params}`)

events.onmessage = (event) => {
  const payload = JSON.parse(event.data)
  if (payload.done) {
    events.close()
    return
  }
  output.textContent += payload.delta
}

두 가지 중단 상황 모두 자동으로 복구됩니다.

  • 네트워크 끊김: EventSource가 스스로 다시 연결하며 Cabby가 각 이벤트에 붙인 Last-Event-ID 헤더를 보냅니다. Cabby는 history_since보다 이 위치를 우선해 브라우저가 놓친 청크만 다시 보냅니다.
  • 페이지 새로고침 또는 다른 기기: 같은 signed_stream과 history_since로 새 EventSource를 열면 실행 시작 시점의 청크부터 모두 재생한 뒤 실시간 토큰으로 전환됩니다.
  • raw=true 옵션: 프로토콜 이벤트(welcome, confirm_subscription)를 생략하고 연결 유지 신호를 SSE 주석(: ping)으로 보내므로, onmessage에는 앱의 JSON 페이로드만 전달됩니다.

5. 긴 스트림, Durable Streams, WebSocket

  • 긴 LLM 응답: --history_limit과 --history_ttl을 높이거나, 50–100 ms 간격으로 토큰을 작은 청크로 묶어 보내면 전체 응답이 기록 범위 안에 넉넉히 들어갑니다.
  • HTTP에서 커서를 직접 관리하기: --ds와 --ds_skip_auth로 Durable Streams를 켠 뒤 GET /ds/runs/<run_id>?offset=-1&live=sse&signed=<signed_stream>을 읽으면 처음부터 재생하면서 각 streamNextOffset을 직접 추적할 수 있습니다.
  • WebSocket: 같은 sign_stream과 broadcast 헬퍼는 Django 가이드처럼 @anycable/web을 통한 WebSocket에서도 그대로 동작합니다.
  • 멀티 노드 Cabby: 단일 서버를 넘어 확장할 때는 --broker=sqlite 대신 Redis, PostgreSQL, NATS를 사용합니다.