跳至主要內容
cabby

FastAPI

當 FastAPI 直接透過 StreamingResponse 串流 AI 回覆時,訊號中斷或重新整理頁面就會讓串流斷在一半。改把 Cabby 放在前面:FastAPI 在 BackgroundTasks 裡執行生成,用 httpx 透過 HTTP 送出每個片段;Cabby 負責維持 Server-Sent Events 連線,並把串流的歷史訊息保存在 SQLite 中,用戶端重新連線或重整頁面都能補齊每個漏掉的片段,完全不需要 Redis。

1. 啟動 Cabby

先安裝 Cabby,再開啟 SSE 與 SQLite broker,以獨立模式啟動:

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,就會從執行開始處重播所有片段,再無縫切換到即時 Token。
  • **raw=true:**省略協定事件(welcome、confirm_subscription),並把心跳改以 SSE 註解(: ping)送出,讓 onmessage 只收到你的 JSON 內容。

5. 長串流、Durable Streams 與 WebSocket

  • **較長的 LLM 回覆:**調高 --history_limit 與 --history_ttl,或每 50–100 ms 將 Token 合併成小片段送出,讓整份回覆都保留在歷史訊息中。
  • **透過 HTTP 明確管理游標:**加上 --ds 與 --ds_skip_auth 開啟 Durable Streams,再讀取 GET /ds/runs/<run_id>?offset=-1&live=sse&signed=<signed_stream>,即可從頭重播並自行追蹤每個 streamNextOffset。
  • **WebSocket:**同樣的 sign_stream 與 broadcast 函式也能搭配 @anycable/web 透過 WebSocket 使用,做法與 Django 指南相同。
  • **多節點 Cabby:**需要擴展超過單台伺服器時,將 --broker=sqlite 換成 Redis、PostgreSQL 或 NATS。