ai newsFr., 4. Dez.
EilmeldungAlibaba Releases Qwen4-35B-A3B: Open-Weight MoE Model With 1M Context

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 no

dev.toFreitag 05:59 · 04.12.7 Min. Lesezeit
Bild: dev.to

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.

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

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.

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.

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.

@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.

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:

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.

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.

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.

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:

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

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

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.

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

Quelle: dev.to (dev.to). Original öffnen