Skip to content

Commit

Permalink
Add support for context manager (#435)
Browse files Browse the repository at this point in the history
* Add support for context manager

* Fix
  • Loading branch information
billytrend-cohere authored Mar 25, 2024
1 parent b6b5090 commit 2eac37d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/cohere/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ def __init__(

validate_args(self, "chat", throw_if_stream_is_true)

# support context manager until Fern upstreams
# https://linear.app/buildwithfern/issue/FER-1242/expose-a-context-manager-interface-or-the-http-client-easily
def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
self._client_wrapper.httpx_client.httpx_client.close()

wait = wait

"""
Expand Down Expand Up @@ -161,6 +169,14 @@ def __init__(

validate_args(self, "chat", throw_if_stream_is_true)

# support context manager until Fern upstreams
# https://linear.app/buildwithfern/issue/FER-1242/expose-a-context-manager-interface-or-the-http-client-easily
async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc_value, traceback):
await self._client_wrapper.httpx_client.httpx_client.aclose()

wait = async_wait

"""
Expand Down
4 changes: 4 additions & 0 deletions tests/test_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ async def test_token_falls_back_on_env_variable(self) -> None:
cohere.AsyncClient(api_key=None)
cohere.AsyncClient(None)

async def test_context_manager(self) -> None:
async with cohere.AsyncClient(api_key="xxx") as client:
self.assertIsNotNone(client)

async def test_chat(self) -> None:
chat = await self.co.chat(
chat_history=[
Expand Down
4 changes: 4 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ def test_token_falls_back_on_env_variable(self) -> None:
cohere.Client(api_key=None)
cohere.Client(None)

def test_context_manager(self) -> None:
with cohere.Client(api_key="xxx") as client:
self.assertIsNotNone(client)

def test_chat(self) -> None:
chat = co.chat(
chat_history=[
Expand Down

0 comments on commit 2eac37d

Please sign in to comment.