Skip to content

Client(timeout=...) raises raw httpx.ReadTimeout instead of an ollama exception #803

Open

Description

@Yeshajagad

What happens

When I set timeout on ollama.Client or ollama.AsyncClient and the server takes longer than that to respond, the call raises a raw httpx.ReadTimeout. Connection failures, on the other hand, are converted into a builtin ConnectionError with a helpful message. So callers have to import httpx just to catch timeouts, even though the library otherwise hides it.

timeout defaults to None, so this only shows up when a user sets it explicitly, which is common with slow local models.

Environment

  • Python: 3.13.5
  • ollama-python: 0.6.3
  • httpx: 0.28.1
  • OS: macOS (Apple Silicon, arm64)

Reproduction

No Ollama model needed. This script starts a local server that waits 3 seconds before replying, and the client uses timeout=0.5. It also checks a connection error (nothing listening on the port) for comparison:

import asyncio
import socket
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from importlib.metadata import version

import httpx
import ollama


class SlowHandler(BaseHTTPRequestHandler):
    """Pretends to be a slow Ollama server: waits 3s before replying."""

    def do_POST(self):
        self.rfile.read(int(self.headers.get("Content-Length", 0)))
        time.sleep(3)
        try:
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(b"{}")
        except Exception:
            pass

    def log_message(self, *args):
        pass


server = ThreadingHTTPServer(("127.0.0.1", 0), SlowHandler)
threading.Thread(target=server.serve_forever, daemon=True).start()
SLOW = f"http://127.0.0.1:{server.server_port}"

# a port with nothing listening, to trigger a connection error
s = socket.socket()
s.bind(("127.0.0.1", 0))
DEAD = f"http://127.0.0.1:{s.getsockname()[1]}"
s.close()

MSG = [{"role": "user", "content": "hi"}]


def report(name, fn):
    try:
        fn()
        print(f"{name:<28} no exception")
    except BaseException as e:
        t = type(e)
        print(f"{name:<28} {t.__module__}.{t.__name__}")


def sync_case():
    ollama.Client(host=SLOW, timeout=0.5).chat(model="m", messages=MSG)


def sync_stream():
    for _ in ollama.Client(host=SLOW, timeout=0.5).chat(model="m", messages=MSG, stream=True):
        pass


def async_case():
    async def f():
        await ollama.AsyncClient(host=SLOW, timeout=0.5).chat(model="m", messages=MSG)
    asyncio.run(f())


def async_stream():
    async def f():
        async for _ in await ollama.AsyncClient(host=SLOW, timeout=0.5).chat(
            model="m", messages=MSG, stream=True
        ):
            pass
    asyncio.run(f())


def connect_case():
    ollama.Client(host=DEAD).chat(model="m", messages=MSG)


def connect_stream():
    for _ in ollama.Client(host=DEAD).chat(model="m", messages=MSG, stream=True):
        pass


print(f"Python {sys.version.split()[0]}, ollama {version('ollama')}, httpx {httpx.__version__}\n")
report("timeout: sync", sync_case)
report("timeout: sync stream", sync_stream)
report("timeout: async", async_case)
report("timeout: async stream", async_stream)
report("connect error: sync", connect_case)
report("connect error: stream", connect_stream)

if "--traceback" in sys.argv:
    print("\n--- full traceback ---")
    ollama.Client(host=SLOW, timeout=0.5).chat(model="m", messages=MSG)

Results

Exception type raised in each case:

timeout: sync                httpx.ReadTimeout
timeout: sync stream         httpx.ReadTimeout
timeout: async               httpx.ReadTimeout
timeout: async stream        httpx.ReadTimeout
connect error: sync          builtins.ConnectionError
connect error: stream        httpx.ConnectError

Traceback for the plain sync case (python repro_timeout.py --traceback, trimmed to the last frames):

  ...
  File ".../site-packages/ollama/_client.py", line 203, in _request
    return cls(**self._request_raw(*args, **kwargs).json())
                 ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File ".../site-packages/ollama/_client.py", line 143, in _request_raw
    r = self._client.request(*args, **kwargs)
  File ".../site-packages/httpx/_client.py", line 825, in request
    return self.send(request, auth=auth, follow_redirects=follow_redirects)
           ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../site-packages/httpx/_client.py", line 914, in send
    response = self._send_handling_auth(
        request,
    ...<2 lines>...
        history=[],
    )
  File ".../site-packages/httpx/_client.py", line 942, in _send_handling_auth
    response = self._send_handling_redirects(
        request,
        follow_redirects=follow_redirects,
        history=history,
    )
  File ".../site-packages/httpx/_client.py", line 979, in _send_handling_redirects
    response = self._send_single_request(request)
  File ".../site-packages/httpx/_client.py", line 1014, in _send_single_request
    response = transport.handle_request(request)
  File ".../site-packages/httpx/_transports/default.py", line 249, in handle_request
    with map_httpcore_exceptions():
         ~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/opt/homebrew/Cellar/python@3.13/3.13.5/Frameworks/Python.framework/Versions/3.13/lib/python3.13/contextlib.py", line 162, in __exit__
    self.gen.throw(value)
    ~~~~~~~~~~~~~~^^^^^^^
  File ".../site-packages/httpx/_transports/default.py", line 118, in map_httpcore_exceptions
    raise mapped_exc(message) from exc
httpx.ReadTimeout: timed out

Expected vs actual

  • Expected: a timeout surfaces as an ollama-level or builtin exception, consistent with how ConnectError is handled.
  • Actual: httpx.ReadTimeout leaks out of all four paths (sync, sync stream, async, async stream).

Related observation

ConnectError is wrapped only on the non-streaming path. In _request_raw (sync and async) it is caught and re-raised as ConnectionError, but the streaming inner() functions catch only HTTPStatusError, so a connection failure while streaming surfaces as httpx.ConnectError (see the last row of my results). It's the same inconsistency, but I'd treat it as a separate question.

Context

I read _client.py on current main: the error handling matches what I see in the installed release, and there is no handling of timeout exceptions anywhere in the file. This looks related to #722, which discusses callers not needing to catch httpx types because errors are converted at the boundary; timeouts seem to be a gap in that.

Proposal

Catch httpx.TimeoutException (parent of ReadTimeout, ConnectTimeout, WriteTimeout and PoolTimeout) in the same places ConnectError is handled, and raise a TimeoutError with the original kept as __cause__. The change would cover Client and AsyncClient, regular and streaming requests, with tests for each.

Questions before I open a PR:

  1. Is a builtin TimeoutError the right type, or would you prefer a custom exception?
  2. Should the streaming ConnectError gap be fixed in the same PR, or separately?
  3. Is the compatibility change acceptable? Code that currently catches httpx.ReadTimeout directly would stop catching it, though the original exception stays reachable via __cause__.

Happy to send the PR if this direction is welcome.

Activity

  1. added a commit that references this issue on Nov 25, 2026
    337ea93
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions