From 6b8484ca42855285a2f869b6e7faf2d7ed5abd28 Mon Sep 17 00:00:00 2001 From: ServOMorph Date: Tue, 4 Nov 2025 21:14:41 +0100 Subject: [PATCH] feat: add close() method and context manager support to Client and AsyncClient - Add close() method to Client and AsyncClient for explicit resource cleanup - Implement __enter__/__exit__ for Client to support context manager usage - Implement __aenter__/__aexit__ for AsyncClient to support async context manager usage - Allows usage: with Client() as client: ... - Allows usage: async with AsyncClient() as client: ... Closes #532 --- ollama/_client.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/ollama/_client.py b/ollama/_client.py index dcd8126..640b387 100644 --- a/ollama/_client.py +++ b/ollama/_client.py @@ -124,6 +124,19 @@ class Client(BaseClient): def __init__(self, host: Optional[str] = None, **kwargs) -> None: super().__init__(httpx.Client, host, **kwargs) + def close(self) -> None: + """Close the underlying HTTP client and release resources.""" + self._client.close() + + def __enter__(self): + """Support usage as a context manager.""" + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Ensure the client is closed when exiting the context.""" + self.close() + return False + def _request_raw(self, *args, **kwargs): try: r = self._client.request(*args, **kwargs) @@ -686,6 +699,19 @@ class AsyncClient(BaseClient): def __init__(self, host: Optional[str] = None, **kwargs) -> None: super().__init__(httpx.AsyncClient, host, **kwargs) + async def close(self) -> None: + """Close the underlying HTTP client and release resources.""" + await self._client.aclose() + + async def __aenter__(self): + """Support usage as an async context manager.""" + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + """Ensure the client is closed when exiting the async context.""" + await self.close() + return False + async def _request_raw(self, *args, **kwargs): try: r = await self._client.request(*args, **kwargs)