| 1 |
from collections.abc import AsyncIterable |
| 2 |
|
| 3 |
from fastapi import FastAPI |
| 4 |
from fastapi.sse import EventSourceResponse, ServerSentEvent |
| 5 |
from pydantic import BaseModel |
| 6 |
|
| 7 |
app = FastAPI() |
| 8 |
|
| 9 |
|
| 10 |
class Prompt(BaseModel): |
| 11 |
text: str |
| 12 |
|
| 13 |
|
| 14 |
@app.post("/chat/stream", response_class=EventSourceResponse) |
| 15 |
async def stream_chat(prompt: Prompt) -> AsyncIterable[ServerSentEvent]: |
| 16 |
words = prompt.text.split() |
| 17 |
for word in words: |
| 18 |
yield ServerSentEvent(data=word, event="token") |
| 19 |
yield ServerSentEvent(raw_data="[DONE]", event="done") |