Skip to content

Commit 37c7817

Browse files
committed
client: expose resource cleanup methods
1 parent 0561f42 commit 37c7817

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

ollama/_client.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,15 @@ class Client(BaseClient):
113113
def __init__(self, host: Optional[str] = None, **kwargs) -> None:
114114
super().__init__(httpx.Client, host, **kwargs)
115115

116+
def close(self):
117+
self._client.close()
118+
119+
def __enter__(self):
120+
return self
121+
122+
def __exit__(self, exc_type, exc_val, exc_tb):
123+
self.close()
124+
116125
def _request_raw(self, *args, **kwargs):
117126
try:
118127
r = self._client.request(*args, **kwargs)
@@ -617,6 +626,15 @@ class AsyncClient(BaseClient):
617626
def __init__(self, host: Optional[str] = None, **kwargs) -> None:
618627
super().__init__(httpx.AsyncClient, host, **kwargs)
619628

629+
async def close(self):
630+
await self._client.aclose()
631+
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+
620638
async def _request_raw(self, *args, **kwargs):
621639
try:
622640
r = await self._client.request(*args, **kwargs)

tests/test_client.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1140,3 +1140,33 @@ async def test_async_client_connection_error():
11401140
with pytest.raises(ConnectionError) as exc_info:
11411141
await client.show('model')
11421142
assert str(exc_info.value) == 'Failed to connect to Ollama. Please check that Ollama is downloaded, running and accessible. https://ollama.com/download'
1143+
1144+
1145+
def test_client_close():
1146+
client = Client()
1147+
client.close()
1148+
assert client._client.is_closed
1149+
1150+
1151+
@pytest.mark.asyncio
1152+
async def test_async_client_close():
1153+
client = AsyncClient()
1154+
await client.close()
1155+
assert client._client.is_closed
1156+
1157+
1158+
def test_client_context_manager():
1159+
with Client() as client:
1160+
assert isinstance(client, Client)
1161+
assert not client._client.is_closed
1162+
1163+
assert client._client.is_closed
1164+
1165+
1166+
@pytest.mark.asyncio
1167+
async def test_async_client_context_manager():
1168+
async with AsyncClient() as client:
1169+
assert isinstance(client, AsyncClient)
1170+
assert not client._client.is_closed
1171+
1172+
assert client._client.is_closed

0 commit comments

Comments
 (0)