Otus specialists analyzed five critical Ollama client mistakes where HTTP 200 is returned but the response is invalid or incomplete. The problem is that Ollama streams NDJSON (Newline Delimited JSON) — each chunk is a separate JSON object, and the client must correctly assemble the stream up to the `done: true` completion marker. In production this leads to subtle bugs: truncated responses, context loss, incorrect tool calls. The article demonstrates this on two real NDJSON responses, showing how to detect completion after HTTP 200, verify stream termination and return the first preserved result on retry.
Related: Ollama, LM Studio, llama.cpp guide
Related: local deployment for sensitive data
Mistake 1: Ignoring the done Flag in NDJSON Response
Ollama API `/api/generate` and `/api/chat` return a line-by-line stream, each line a valid JSON with fields `response` (text chunk), `done` (boolean), `done_reason` (string: `stop`, `length`, `error`). Many clients read the stream in a loop `for line in response.iter_lines()`, parse JSON, concatenate `response`, but do not verify `done: true` before returning. If the connection drops mid-stream (proxy timeout, server OOM, network glitch), the client gets HTTP 200 (headers already sent) but the body breaks without the final chunk. Result — a truncated response that appears valid.
Correct pattern: buffer chunks, after each JSON parse check `if chunk.get(‘done’): break`. Only after explicit `done: true` consider the response complete. In Go this is `for { line, err := reader.ReadBytes(‘\n’); if err != nil { return partial, err }; var chunk map[string]interface{}; json.Unmarshal(line, &chunk); if chunk[“done”] == true { break } }`. In Python — `for line in response.iter_lines(): data = json.loads(line); if data.get(“done”): break`.
Mistake 2: Missing Validation of Completion via done_reason
Even if `done: true` is received, `done_reason` can be `length` (truncated by max_tokens), `error` (internal model error) or `stop` (normal completion). Clients often ignore this field. When `done_reason: “error”` the response may contain an `error` field with description (e.g., `context length exceeded` or `model not found`), but HTTP code remains 200. Must log `done_reason != “stop”` as warning and on `error` raise exception for retry logic.
Example from article: a request with 32k context on an 8k limit model returned `done: true, done_reason: “length”, response: “…”` — client accepted this as success, but response was cut at the limit. Correct handling: on `length` — truncate history and retry, on `error` — read `error` field and decide: switch model, reduce prompt, alert.
Mistake 3: No Idempotency and First Result Caching
On network failure clients often just retry with exponential backoff. But generation already started on server, tokens spent, context lost. Repeat request gives different response (temperature > 0), spends more limits and time. Solution — cache first successful response (after `done: true`) in local cache with key `hash(prompt + model + params)`. On retry (any network error, timeout, 5xx) — return cached result instead of regenerating. Cache TTL — 24 hours or until prompt change.
Article shows Redis implementation: `SETEX ollama:cache:{hash} 86400 “{response_json}”`. On incoming request first `GET`, if exists — return immediately. This is critical for agent pipelines where the same prompt may run 3-5 times due to unstable network. Coupled with the request deduplication and caching approach.
Mistake 4: Incorrect tool_calls Handling in Streaming
Ollama supports tool calling (functions) in OpenAI format: chunks contain `message.tool_calls` with accumulated arguments. Mistake — treat `tool_calls` as plain text, concatenating argument strings by index. JSON arguments break: `{“name”:”get_weather”,”arguments”:”{\\”city\\”:\\”” + `Moscow`”}”` → `{“city”:”Moscow”}` becomes invalid. Correct: accumulate `tool_calls` as structures, merge `arguments` by index, at the end parse full JSON. If parsing fails — treat stream as broken, retry.
Correct merge pseudocode: `for chunk in stream: for tc in chunk.get(“message”,{}).get(“tool_calls”,[]): idx = tc[“index”]; if idx >= len(accumulated): accumulated.append(tc); else: accumulated[idx][“function”][“arguments”] += tc[“function”][“arguments”]`. At the end `for tc in accumulated: json.loads(tc[“function”][“arguments”])` — validation.
Mistake 5: Missing Timeouts at Chunk Level
HTTP clients often set overall request timeout (e.g., 60s) but no inter-chunk timeout. Ollama can “hang” for 2-5 minutes during long reasoning generation (DeepSeek R1, Qwen3 Thinking) — server holds connection but sends no data. Client waits indefinitely, consuming connection pool resources. Need `read_timeout` for next byte/line (e.g., 30s) and `stream_timeout` for total stream duration (e.g., 300s). On trigger — drop connection, log `stream_timeout`, trigger retry with cache (error 3).
httpx (Python) config: `httpx.Client(timeout=httpx.Timeout(connect=10, read=30, write=10, pool=300))`. In Go: `http.Client{Transport: &http.Transport{ResponseHeaderTimeout: 10*time.Second}, Timeout: 300*time.Second}` + manual `SetReadDeadline` in read loop. This prevents worker process hangs under load.
Production-Ready Ollama Client Checklist
- `done: true` check mandatory before returning response.
- Validate `done_reason == “stop”`, alert on `length`/`error`.
- Cache full response by prompt+model+params hash, return from cache on any retry.
- Parse `tool_calls` as structures, validate argument JSON at the end.
- Timeouts: read timeout 30s, stream timeout 300s, connect 10s.
- Log every request: model, prompt_hash, tokens_in/out, latency, done_reason, from_cache.
- Prometheus metrics: `ollama_requests_total{status=”ok|error|cached”}`, `ollama_stream_duration_seconds`, `ollama_chunks_received`.
Monitoring integration: add Grafana dashboard on `ollama_stream_duration_seconds` with alert `p99 > 120s` — indicates model or hardware issue. For local model resource sizing use RAM calculation formula for models to avoid OOM mid-stream. When working with sensitive codebases follow local deployment for sensitive data — Ollama on isolated host without outbound internet.
Useful resources: Ollama repository and docs, MDN HTTP status reference.
Reliable Ollama client pattern: • Cache key = hash(model + messages + options). • Check Redis cache first. • Stream with timeouts (connect=10s, read=30s, pool=300s). • Read line by line, check done:true. • Validate done_reason == “stop”. • Parse tool_calls as structures. • Save to cache with 24h TTL. This eliminates all 5 errors.

