Skip to content

Commit d49dca0

Browse files
Python: Preserve synchronous chat client cleanup compatibility
1 parent 8b2a429 commit d49dca0

4 files changed

Lines changed: 60 additions & 3 deletions

File tree

‎python/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ agent contexts sharing a connector-owned connection, since exiting either agent
196196
an SDK client across agents, inject it into their chat clients and manage its lifetime outside those agent contexts.
197197
`BaseChatClient` provides default context methods and a no-op `close()`, so custom subclasses do not need to
198198
implement lifecycle methods unless they own resources. Protocol-only chat clients do not need context methods.
199+
Inherited context exit also supports existing subclasses whose `close()` is synchronous.
199200

200201
## 4. Build an Agent with Tools and Functions
201202

‎python/packages/core/agent_framework/_clients.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
Mapping,
1313
Sequence,
1414
)
15+
from inspect import isawaitable
1516
from types import TracebackType
1617
from typing import (
1718
TYPE_CHECKING,
@@ -327,13 +328,16 @@ async def __aexit__(
327328
/,
328329
) -> None:
329330
"""Release resources owned by the client without suppressing exceptions."""
330-
await self.close()
331+
result = self.close()
332+
if isawaitable(result):
333+
await result
331334

332335
async def close(self) -> None:
333336
"""Release client-owned connections and credentials.
334337
335338
The default implementation does nothing. Resource-owning implementations
336339
override this method and must leave caller-supplied resources open.
340+
Context exit also accepts legacy synchronous ``close()`` overrides.
337341
Clients remain usable without entering an async context; callers can use
338342
``await client.close()`` to release their resources explicitly.
339343
"""

‎python/packages/core/tests/core/test_agents.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,24 @@ async def test_agent_still_accepts_client_without_lifecycle(client: SupportsChat
249249
assert response.text == "test response"
250250

251251

252+
@pytest.mark.parametrize("agent_type", [Agent, RawAgent])
253+
@pytest.mark.parametrize("error", [None, RuntimeError("body failed")])
254+
async def test_agent_context_accepts_client_with_sync_close(
255+
agent_type: type[RawAgent], chat_client_base: MockBaseChatClient, error: RuntimeError | None
256+
) -> None:
257+
with patch.object(chat_client_base, "close", new_callable=MagicMock, return_value=None) as close:
258+
agent = agent_type(client=chat_client_base)
259+
if error is None:
260+
async with agent:
261+
close.assert_not_called()
262+
else:
263+
with pytest.raises(RuntimeError) as raised:
264+
async with agent:
265+
raise error
266+
assert raised.value is error
267+
close.assert_called_once_with()
268+
269+
252270
@pytest.mark.parametrize("agent_type", [Agent, RawAgent])
253271
async def test_agent_async_with_delegates_to_open_close(agent_type: type[RawAgent]) -> None:
254272
events: list[str] = []

‎python/packages/core/tests/core/test_clients.py‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import asyncio
66
import logging
77
from typing import Any
8-
from unittest.mock import AsyncMock, patch
8+
from unittest.mock import AsyncMock, MagicMock, patch
99

1010
import pytest
1111

@@ -129,7 +129,7 @@ async def test_base_client_default_lifecycle(chat_client_base: BaseChatClient) -
129129
assert (await chat_client_base.get_response([Message("user", ["Again"])])).text == "test response - Again"
130130

131131

132-
@pytest.mark.parametrize("error", [None, RuntimeError("body failed"), asyncio.CancelledError()])
132+
@pytest.mark.parametrize("error", [None, RuntimeError("body failed")])
133133
async def test_base_client_context_calls_close(chat_client_base: BaseChatClient, error: BaseException | None) -> None:
134134
with patch.object(chat_client_base, "close", new_callable=AsyncMock) as close:
135135
if error is None:
@@ -143,6 +143,40 @@ async def test_base_client_context_calls_close(chat_client_base: BaseChatClient,
143143
close.assert_awaited_once_with()
144144

145145

146+
async def test_base_client_context_closes_on_cancellation(chat_client_base: BaseChatClient) -> None:
147+
entered = asyncio.Event()
148+
149+
async def run_client() -> None:
150+
async with chat_client_base:
151+
entered.set()
152+
await asyncio.Event().wait()
153+
154+
with patch.object(chat_client_base, "close", new_callable=AsyncMock) as close:
155+
task = asyncio.create_task(run_client())
156+
await entered.wait()
157+
task.cancel()
158+
with pytest.raises(asyncio.CancelledError):
159+
await task
160+
assert task.cancelled()
161+
close.assert_awaited_once_with()
162+
163+
164+
@pytest.mark.parametrize("error", [None, RuntimeError("body failed")])
165+
async def test_base_client_context_accepts_sync_close(
166+
chat_client_base: BaseChatClient, error: RuntimeError | None
167+
) -> None:
168+
with patch.object(chat_client_base, "close", new_callable=MagicMock, return_value=None) as close:
169+
if error is None:
170+
async with chat_client_base:
171+
close.assert_not_called()
172+
else:
173+
with pytest.raises(RuntimeError) as raised:
174+
async with chat_client_base:
175+
raise error
176+
assert raised.value is error
177+
close.assert_called_once_with()
178+
179+
146180
async def test_base_client_context_propagates_cleanup_failure(chat_client_base: BaseChatClient) -> None:
147181
with (
148182
patch.object(chat_client_base, "close", new_callable=AsyncMock, side_effect=RuntimeError("close failed")),

0 commit comments

Comments
 (0)