Skip to content

Commit 1a047b0

Browse files
committed
client: use contextlib for resource management
1 parent b0ba425 commit 1a047b0

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

ollama/_client.py

+11-13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import ipaddress
23
import json
34
import os
@@ -70,7 +71,7 @@
7071
T = TypeVar('T')
7172

7273

73-
class BaseClient:
74+
class BaseClient(contextlib.AbstractContextManager):
7475
def __init__(
7576
self,
7677
client,
@@ -105,6 +106,15 @@ def __init__(
105106
**kwargs,
106107
)
107108

109+
def __exit__(self, exc_type, exc_val, exc_tb):
110+
self.close()
111+
112+
async def __aenter__(self) -> Any:
113+
return self
114+
115+
async def __aexit__(self, exc_type, exc_val, exc_tb):
116+
await self.close()
117+
108118

109119
CONNECTION_ERROR_MESSAGE = 'Failed to connect to Ollama. Please check that Ollama is downloaded, running and accessible. https://ollama.com/download'
110120

@@ -116,12 +126,6 @@ def __init__(self, host: Optional[str] = None, **kwargs) -> None:
116126
def close(self):
117127
self._client.close()
118128

119-
def __enter__(self):
120-
return self
121-
122-
def __exit__(self, exc_type, exc_val, exc_tb):
123-
self.close()
124-
125129
def _request_raw(self, *args, **kwargs):
126130
try:
127131
r = self._client.request(*args, **kwargs)
@@ -629,12 +633,6 @@ def __init__(self, host: Optional[str] = None, **kwargs) -> None:
629633
async def close(self):
630634
await self._client.aclose()
631635

632-
async def __aenter__(self):
633-
return self
634-
635-
async def __aexit__(self, exc_type, exc_val, exc_tb):
636-
await self.close()
637-
638636
async def _request_raw(self, *args, **kwargs):
639637
try:
640638
r = await self._client.request(*args, **kwargs)

0 commit comments

Comments
 (0)