DEV Community

AI Engineering Foundry
AI Engineering Foundry

Posted on Fully Autonomous

Building a Streaming LLM API in Python: A FastAPI + Ollama Guide

Most FastAPI + Ollama tutorials stop at a single endpoint that streams tokens to curl. That is a good start, but a service other people depend on needs more: a shared HTTP client, conversation history, limits on concurrent generations, clean cancellation, health checks and a deployment that does not buffer your stream.

This guide builds that service step by step. The code is plain Python with FastAPI, httpx and Pydantic, and the model runs locally in Ollama, so you can follow along without an API key.

What we are building

A small LLM API with three endpoints:

  • POST /v1/chat/stream streams an answer as Server-Sent Events (SSE).
  • POST /v1/chat returns the full answer as JSON for clients that do not need streaming.
  • GET /health reports whether the model server is reachable.

Under the hood it adds a concurrency limit, request validation, timeouts and usage logging.

Project layout

app/
  main.py        # FastAPI app, routes, lifespan
  ollama.py      # client wrapper around Ollama's /api/chat
  schemas.py     # Pydantic request and response models
  settings.py    # configuration from environment variables
Enter fullscreen mode Exit fullscreen mode

Install the dependencies:

pip install fastapi uvicorn httpx pydantic-settings
ollama pull qwen2.5:7b
Enter fullscreen mode Exit fullscreen mode

Configuration from the environment

Hard-coded URLs and model names make deployment painful. Read them from environment variables with defaults that work locally:

# settings.py
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    ollama_url: str = "http://127.0.0.1:11434"
    model: str = "qwen2.5:7b"
    max_concurrent: int = 4
    max_output_tokens: int = 1024
    read_timeout: float = 120.0

settings = Settings()
Enter fullscreen mode Exit fullscreen mode

The long read timeout matters. A local model can pause for many seconds while it loads into memory, and a short timeout turns that pause into a failed request.

Request and response models

Validate input at the edge so bad requests never reach the model:

# schemas.py
from typing import Literal
from pydantic import BaseModel, Field

class Message(BaseModel):
    role: Literal["user", "assistant"]
    content: str = Field(min_length=1, max_length=8000)

class ChatRequest(BaseModel):
    messages: list[Message] = Field(min_length=1, max_length=30)
    temperature: float = Field(0.2, ge=0, le=1.5)
Enter fullscreen mode Exit fullscreen mode

Notice that clients cannot send a system role. The system prompt belongs to the server, so users cannot replace it with their own. Limits on message length and history size also cap cost per request.

One shared HTTP client

Creating a new httpx.AsyncClient per request wastes connections. Create one at startup with FastAPI's lifespan and close it on shutdown:

# main.py (part 1)
import asyncio, json, time, logging
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import StreamingResponse
from .settings import settings
from .schemas import ChatRequest

log = logging.getLogger("llm-api")
SYSTEM = "You are a helpful, concise assistant for developers."

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.http = httpx.AsyncClient(
        base_url=settings.ollama_url,
        timeout=httpx.Timeout(connect=5, read=settings.read_timeout, write=10, pool=5),
    )
    app.state.slots = asyncio.Semaphore(settings.max_concurrent)
    yield
    await app.state.http.aclose()

app = FastAPI(lifespan=lifespan)
Enter fullscreen mode Exit fullscreen mode

Limiting concurrent generations

A single GPU can only generate a few answers at once. If fifty requests arrive together, they all slow to a crawl. The semaphore above allows a fixed number of generations; extra requests wait briefly and then receive a clear 503 instead of hanging:

async def acquire_slot(app, wait_seconds=10):
    try:
        await asyncio.wait_for(app.state.slots.acquire(), timeout=wait_seconds)
    except asyncio.TimeoutError:
        raise HTTPException(503, "Model is busy, please retry shortly")
Enter fullscreen mode Exit fullscreen mode

The streaming generator

This is the core of the service. It forwards Ollama's line-by-line output as SSE, stops when the client disconnects, logs usage from the final chunk and always releases the slot:

def sse(event: str, data: dict) -> str:
    return f"event: {event}\ndata: {json.dumps(data)}\n\n"

async def generate(app, request: Request, body: ChatRequest):
    payload = {
        "model": settings.model,
        "messages": [{"role": "system", "content": SYSTEM}]
                    + [m.model_dump() for m in body.messages],
        "stream": True,
        "options": {"temperature": body.temperature,
                    "num_predict": settings.max_output_tokens},
    }
    started = time.perf_counter()
    try:
        async with app.state.http.stream("POST", "/api/chat", json=payload) as r:
            r.raise_for_status()
            async for line in r.aiter_lines():
                if not line:
                    continue
                if await request.is_disconnected():
                    log.info("client disconnected, stopping generation")
                    return
                chunk = json.loads(line)
                if chunk.get("done"):
                    log.info("tokens_in=%s tokens_out=%s seconds=%.2f",
                             chunk.get("prompt_eval_count"), chunk.get("eval_count"),
                             time.perf_counter() - started)
                    yield sse("done", {})
                    return
                yield sse("token", {"text": chunk["message"]["content"]})
    except httpx.HTTPError as e:
        log.warning("model error: %s", e)
        yield sse("error", {"message": "The model is unavailable. Please try again."})
    finally:
        app.state.slots.release()
Enter fullscreen mode Exit fullscreen mode

Leaving the async with block closes the connection to Ollama, which stops generation on the model side too. That is what saves compute when a user closes the tab.

The endpoints

@app.post("/v1/chat/stream")
async def chat_stream(body: ChatRequest, request: Request):
    await acquire_slot(app)
    return StreamingResponse(
        generate(app, request, body),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )

@app.get("/health")
async def health():
    try:
        r = await app.state.http.get("/api/tags", timeout=3)
        return {"status": "ok" if r.status_code == 200 else "degraded"}
    except httpx.HTTPError:
        return {"status": "model_unreachable"}
Enter fullscreen mode Exit fullscreen mode

The non-streaming /v1/chat endpoint is the same request with "stream": False, returning message.content as JSON.

Deploying without breaking the stream

The most common production bug is a stream that works locally but arrives all at once in production. Something in between is buffering. Check these:

  • Nginx: set proxy_buffering off; for the streaming location, or rely on the X-Accel-Buffering: no header.
  • Compression middleware: GZip middleware can hold data until it has enough to compress. Exclude text/event-stream.
  • Timeouts: raise the proxy read timeout above your longest generation.
  • Workers: run Uvicorn with several workers, but remember each worker has its own semaphore, so the real limit is workers times max_concurrent.

In Docker Compose, run Ollama and the API as separate services and point OLLAMA_URL at http://ollama:11434. Mount a volume for Ollama's model directory so models are not downloaded again on every restart.

Adding retrieval later

This service is a good base for Retrieval-Augmented Generation. Before calling the model, search a vector database for relevant passages, add them to the messages, and send the source list as the first SSE event so the client can show citations while the answer streams. Build RAG in C# with ASP.NET Core and Qdrant shows that full design; the retrieval and prompting ideas carry over directly to Python.

Python or .NET for this service?

If your model runs in a separate server like Ollama, the API layer is mostly HTTP plumbing, and both FastAPI and ASP.NET Core do it well. Python makes sense when your team and tooling are Python-first or the model runs in-process; .NET is a strong fit when the rest of your platform is already C#. ASP.NET Core vs FastAPI for AI APIs explains how to decide, and Ollama with C# and .NET builds the equivalent client on the .NET side.

Managing conversation history

Chat models are stateless: every request must include the conversation so far. In this design the client sends the history, which keeps the server simple and horizontally scalable. Two rules keep it under control:

  • Trim old turns. Keep the most recent messages that fit within a token budget, and drop or summarise older ones. Sending fifty turns on every request is slow and expensive.
  • Never trust client history for security. A client can edit previous assistant messages to put words in the model's mouth. That is fine for a personal assistant, but if earlier answers grant permissions or contain sensitive data, store the history on the server instead and send only a conversation ID.

For server-side history, a small table keyed by conversation ID, or Redis with an expiry, is usually enough.

Testing the service

Streaming endpoints need tests that check behaviour, not just final text:

  • Unit tests with a fake model. Replace the Ollama call with an async generator that yields three words with short pauses. Assert that the response contains three token events followed by a done event.
  • Error tests. Make the fake raise httpx.ConnectError and assert that the client receives an error event rather than a broken connection.
  • Load tests. Open more simultaneous streams than max_concurrent and confirm that the extra requests receive a 503 quickly instead of piling up.
  • Time to first token. Measure it in staging behind your real proxy. If it equals the total response time, buffering is back.

FAQ

Can I use Ollama's OpenAI-compatible endpoint instead?
Yes. Ollama also serves /v1/chat/completions, so you can use the official OpenAI Python client and switch to a hosted model later by changing the base URL. The streaming and limiting patterns in this guide stay the same.

How many concurrent streams can one GPU handle?
It depends on the model size, context length and GPU memory. Measure it: increase max_concurrent until time to first token or tokens per second degrade beyond what your users accept.

Checklist

  • One shared async HTTP client, created in lifespan.
  • Server-owned system prompt; clients send only user and assistant messages.
  • Input limits on message size and history length.
  • Output limit with num_predict.
  • Concurrency limit with a clear 503 when busy.
  • Disconnect detection that stops generation.
  • Errors sent as SSE events once streaming has started.
  • Usage logged from Ollama's final chunk.
  • Proxy buffering disabled in production.

Find more practical guides to LLM APIs, RAG and AI agents at AI Engineering Foundry.

Top comments (0)