Backend Boilerplates python Advanced

OpenAI Streaming Response

Stream a ChatGPT response token-by-token to the client using FastAPI StreamingResponse.

python
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI

app = FastAPI()
client = AsyncOpenAI()

@app.post("/chat")
async def chat(prompt: str):
    async def token_stream():
        async for chunk in await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": prompt}],
            stream=True,
        ):
            delta = chunk.choices[0].delta.content or ""
            if delta:
                yield delta
    return StreamingResponse(token_stream(), media_type="text/plain")

Prerequisites

  • openai >= 1.0
  • fastapi

Pro Tips

  • → Use Server-Sent Events for browser clients.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Advanced
Read time
5 min
Published
Aug 2025
License
Commercial License

Newsletter

New modules every week, directly to your inbox.