Repository navigation
Expand file tree
/
Copy pathopenai_streaming_demo.py
More file actions
156 lines (134 loc) · 4.75 KB
/
Copy pathopenai_streaming_demo.py
File metadata and controls
156 lines (134 loc) · 4.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""
OpenAI & LLM Token Streaming Demo with fastapi-stream-lease
Demonstrates protecting an AI chat streaming endpoint with 1-line lease management:
- Strictly limits concurrent AI generation streams per user.
- Automatically releases leases on completion, abort, or network disconnect.
- Protects LLM token generation budget from multi-tab abuse or runaway scrapers.
Run with:
STREAM_DEMO_TOKEN=secret python -m uvicorn examples.openai_streaming_demo:app --port 8000
"""
from __future__ import annotations
import asyncio
import hmac
import logging
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any
import redis.asyncio as redis
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.security import APIKeyHeader
try:
from openai import AsyncOpenAI
_HAS_OPENAI = True
except ImportError:
AsyncOpenAI = None # type: ignore[assignment,misc]
_HAS_OPENAI = False
from fastapi_stream_lease import (
LeaseConfig,
StreamLeaseManager,
)
logger = logging.getLogger("openai_streaming_demo")
api_key_header = APIKeyHeader(name="X-API-Key")
redis_client = redis.from_url(
os.environ.get("REDIS_URL", "redis://localhost:6379/0"),
socket_timeout=2.0,
socket_connect_timeout=2.0,
)
manager = StreamLeaseManager(
redis_client,
LeaseConfig(
max_per_user=1, # Strictly allow only 1 active LLM generation stream per user
max_global=100, # Cluster-wide safeguard against total LLM capacity exhaustion
lease_seconds=30.0,
acquire_timeout=0.5, # Wait up to 500ms for concurrent bursts before rejecting
include_lease_headers=True, # Attach X-Stream-Lease-Id and limit headers
),
)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Verify cluster configuration consistency at startup
await manager.verify_cluster_config(strict=True)
api_key = os.environ.get("OPENAI_API_KEY")
client: Any = None
if _HAS_OPENAI and api_key and AsyncOpenAI is not None:
client = AsyncOpenAI(api_key=api_key)
logger.info("Initialized shared AsyncOpenAI client connection pool")
app.state.openai_client = client
yield
if client is not None:
await client.close()
# Gracefully drain background tasks and close Redis client
await manager.close(drain=True, timeout=5.0)
if hasattr(redis_client, "aclose"):
await redis_client.aclose()
else:
await redis_client.close()
app = FastAPI(title="LLM Streaming Protection Demo", lifespan=lifespan)
manager.register_exception_handlers(app)
async def authenticated_user(api_key: str = Depends(api_key_header)) -> str:
expected = os.environ.get("STREAM_DEMO_TOKEN")
if not expected or not hmac.compare_digest(api_key, expected):
raise HTTPException(
status_code=401,
detail="Invalid API key (ensure STREAM_DEMO_TOKEN is set in environment)",
)
return "user-enterprise-1"
async def llm_token_stream(prompt: str, client: Any = None) -> AsyncIterator[str]:
"""Streams LLM tokens using the shared AsyncOpenAI client when available,
or falls back to a simulated token stream if unconfigured.
"""
if client is not None:
model = os.environ.get("OPENAI_MODEL", "gpt-4o-mini")
response = await client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async for chunk in response:
content = chunk.choices[0].delta.content or ""
if content:
yield f"data: {content}\n\n"
yield "data: [DONE]\n\n"
return
# Fallback simulation when openai package or OPENAI_API_KEY is not configured
logger.info("OPENAI_API_KEY not detected; running simulated token stream")
tokens = [
"Hello",
"!",
" I",
" am",
" your",
" AI",
" assistant",
".",
" This",
" stream",
" is",
" concurrency",
"-managed",
" by",
" Redis",
" leases",
".\n\n",
]
for token in tokens:
yield f"data: {token}\n\n"
await asyncio.sleep(0.3)
@app.get("/v1/chat/stream")
async def chat_stream(
request: Request,
prompt: str = "Hello",
user_id: str = Depends(authenticated_user),
):
"""
Protected LLM chat completion endpoint.
Uses `await manager.stream(...)` to acquire the lease, wrap the generator,
and return an SSE StreamingResponse in a single, safe call.
"""
client = getattr(request.app.state, "openai_client", None)
return await manager.stream(
user_id=user_id,
stream=llm_token_stream(prompt, client=client),
media_type="text/event-stream",
)