| 1 |
import time |
| 2 |
from typing import Annotated |
| 3 |
|
| 4 |
from fastapi import Depends, FastAPI, HTTPException |
| 5 |
from fastapi.responses import StreamingResponse |
| 6 |
from sqlmodel import Field, Session, SQLModel, create_engine |
| 7 |
|
| 8 |
engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db") |
| 9 |
|
| 10 |
|
| 11 |
class User(SQLModel, table=True): |
| 12 |
id: int | None = Field(default=None, primary_key=True) |
| 13 |
name: str |
| 14 |
|
| 15 |
|
| 16 |
app = FastAPI() |
| 17 |
|
| 18 |
|
| 19 |
def get_session(): |
| 20 |
with Session(engine) as session: |
| 21 |
yield session |
| 22 |
|
| 23 |
|
| 24 |
def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]): |
| 25 |
user = session.get(User, user_id) |
| 26 |
if not user: |
| 27 |
raise HTTPException(status_code=403, detail="Not authorized") |
| 28 |
|
| 29 |
|
| 30 |
def generate_stream(query: str): |
| 31 |
for ch in query: |
| 32 |
yield ch |
| 33 |
time.sleep(0.1) |
| 34 |
|
| 35 |
|
| 36 |
@app.get("/generate", dependencies=[Depends(get_user)]) |
| 37 |
def generate(query: str): |
| 38 |
return StreamingResponse(content=generate_stream(query)) |