Skip to content

Commit a59bb68

Browse files
authored
feat: add httpx2 support (a2aproject#1439)
## Description This PR introduces support to client-passed `httpx2` connection via `httpx_compat` It is backward compatible, which means that passing `httpx` is also valid and exceptions/typing are properly handled The compat layer exports catch-tuples for except/isinstance, type aliases for annotations, and `httpx_lib` The only use of `httpx` is left in 2 places: - When client didn't provide their own connection (so we are leaving it as is) - When checking the status codes (httpx and httpx2 behave the same way here) ## Tests - Restructured tests, so that they use `httpx_lib` from `httpx_compat` - Marked the 35 files whose behavior depends on the installed lib with `@pytest.mark.httpx2.` This includes files that never mention httpx themselves: `starlette.testclient` picks `httpx2` when it is installed, so anything using TestClient is affected too. - Added a CI job that installs the new httpx2 dependency group and reruns those tests. The default matrix installs only dev, so it stays an httpx-only environment. Release-As: 1.4.0 refers to a2aproject#1288
1 parent c16cab1 commit a59bb68

52 files changed

Lines changed: 691 additions & 338 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/linter.yaml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@ jobs:
2525
- name: Set up Python
2626
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v6
2727
with:
28-
python-version-file: .python-version
28+
python-version: '3.11'
2929
- name: Install uv
3030
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7
3131
- name: Add uv to PATH
3232
run: |
3333
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
3434
- name: Install dependencies
35-
run: uv sync --locked
35+
run: uv sync --locked --group httpx2
3636
- name: Run Ruff Linter
3737
id: ruff-lint
3838
run: uv run ruff check --output-format=github

‎.github/workflows/unit-tests.yml‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,39 @@ jobs:
129129

130130
- name: Show coverage summary in log
131131
run: uv run coverage report
132+
133+
# httpx2 testing - Running test on httpx2 for marked tests
134+
httpx2:
135+
name: Test with httpx2 (Python ${{ matrix.python-version }})
136+
runs-on: ubuntu-latest
137+
138+
if: github.repository == 'a2aproject/a2a-python'
139+
140+
strategy:
141+
matrix:
142+
python-version: ['3.11', '3.12', '3.13', '3.14']
143+
steps:
144+
- name: Checkout code
145+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
146+
147+
- name: Install uv for Python ${{ matrix.python-version }}
148+
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7
149+
with:
150+
python-version: ${{ matrix.python-version }}
151+
- name: Add uv to PATH
152+
run: |
153+
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
154+
155+
- name: Install dependencies
156+
run: uv sync --locked --group httpx2
157+
158+
# httpx_lib silently falls back to httpx when httpx2 is missing, thus installing httpx2 is required
159+
- name: Verify httpx2 is the installed flavor
160+
run: |
161+
uv run python -c "
162+
from a2a.utils._httpx_compat import httpx_lib
163+
assert httpx_lib.__name__ == 'httpx2', httpx_lib.__name__
164+
"
165+
166+
- name: Run tests
167+
run: uv run pytest -m httpx2

‎pyproject.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ addopts = "-ra --strict-markers --dist loadgroup"
8585
markers = [
8686
"asyncio: mark a test as a coroutine that should be run by pytest-asyncio",
8787
"xdist_group: mark a test to run in a specific sequential group for isolation",
88+
"httpx2: mark a test whose behavior depends on the installed HTTP client",
8889
]
8990
filterwarnings = [
9091
# SQLAlchemy warning about duplicate class registration - this is a known limitation
@@ -105,6 +106,7 @@ vcs = "git"
105106
style = "pep440"
106107

107108
[dependency-groups]
109+
httpx2 = ["httpx2>=2.0.0,<3 ; python_version >= '3.11'"]
108110
dev = [
109111
"fastapi>=0.115.2",
110112
"PyJWT>=2.0.0",

‎src/a2a/client/card_resolver.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,17 @@
44
from collections.abc import Callable
55
from typing import Any
66

7-
import httpx
8-
97
from google.protobuf.json_format import ParseDict, ParseError
108

119
from a2a.client.errors import AgentCardResolutionError
1210
from a2a.types.a2a_pb2 import (
1311
AgentCard,
1412
)
13+
from a2a.utils._httpx_compat import (
14+
HTTP_STATUS_ERROR,
15+
REQUEST_ERROR,
16+
AsyncClient,
17+
)
1518
from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
1619

1720

@@ -133,14 +136,15 @@ class A2ACardResolver:
133136

134137
def __init__(
135138
self,
136-
httpx_client: httpx.AsyncClient,
139+
httpx_client: AsyncClient,
137140
base_url: str,
138141
agent_card_path: str = AGENT_CARD_WELL_KNOWN_PATH,
139142
) -> None:
140143
"""Initializes the A2ACardResolver.
141144
142145
Args:
143-
httpx_client: An async HTTP client instance (e.g., httpx.AsyncClient).
146+
httpx_client: An async HTTP client instance (`httpx.AsyncClient`
147+
or `httpx2.AsyncClient`).
144148
base_url: The base URL of the agent's host.
145149
agent_card_path: The path to the agent card endpoint, relative to the base URL.
146150
"""
@@ -200,7 +204,7 @@ async def get_agent_card(
200204
agent_card = parse_agent_card(agent_card_data)
201205
if signature_verifier:
202206
signature_verifier(agent_card)
203-
except httpx.HTTPStatusError as e:
207+
except HTTP_STATUS_ERROR as e:
204208
raise AgentCardResolutionError(
205209
f'Failed to fetch agent card from {target_url} (HTTP {e.response.status_code}): {e}',
206210
status_code=e.response.status_code,
@@ -209,7 +213,7 @@ async def get_agent_card(
209213
raise AgentCardResolutionError(
210214
f'Failed to parse JSON for agent card from {target_url}: {e}'
211215
) from e
212-
except httpx.RequestError as e:
216+
except REQUEST_ERROR as e:
213217
raise AgentCardResolutionError(
214218
f'Network communication error fetching agent card from {target_url}: {e}',
215219
) from e

‎src/a2a/client/client.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
from types import TracebackType
77
from typing import Any
88

9-
import httpx
10-
119
from pydantic import BaseModel, Field
1210
from typing_extensions import Self
1311

@@ -31,6 +29,7 @@
3129
Task,
3230
TaskPushNotificationConfig,
3331
)
32+
from a2a.utils._httpx_compat import AsyncClient
3433

3534

3635
logger = logging.getLogger(__name__)
@@ -48,7 +47,7 @@ class ClientConfig:
4847
the callers job to check if the response is completed and if not run a
4948
polling loop."""
5049

51-
httpx_client: httpx.AsyncClient | None = None
50+
httpx_client: AsyncClient | None = None
5251
"""Http client to use to connect to agent."""
5352

5453
grpc_channel_factory: Callable[[str], Channel] | None = None

‎src/a2a/client/client_factory.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333

3434
if TYPE_CHECKING:
3535
from a2a.client.interceptors import ClientCallInterceptor
36+
from a2a.utils._httpx_compat import AsyncClient
3637

3738

3839
try:
@@ -96,7 +97,7 @@ def __init__(
9697
self._registry: dict[str, TransportProducer] = {}
9798
self._register_defaults(config.supported_protocol_bindings)
9899

99-
def _resolve_http_client(self) -> tuple[httpx.AsyncClient, bool]:
100+
def _resolve_http_client(self) -> tuple[AsyncClient, bool]:
100101
"""Returns an HTTP client and whether it is shared across clients."""
101102
if self._config.httpx_client:
102103
return self._config.httpx_client, True

‎src/a2a/client/transports/http_helpers.py‎

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,19 @@
33

44
from collections.abc import AsyncGenerator, Callable, Iterator
55
from contextlib import contextmanager
6-
from typing import Any, NoReturn
7-
8-
import httpx
6+
from typing import TYPE_CHECKING, Any, NoReturn
97

108
from a2a.client.client import ClientCallContext
119
from a2a.client.errors import A2AClientError, A2AClientTimeoutError
10+
from a2a.utils._httpx_compat import (
11+
HTTP_STATUS_ERROR,
12+
REQUEST_ERROR,
13+
TIMEOUT_EXCEPTION,
14+
AsyncClient,
15+
HTTPStatusError,
16+
Request,
17+
Response,
18+
)
1219

1320

1421
def _default_sse_error_handler(sse_data: str) -> NoReturn:
@@ -17,25 +24,24 @@ def _default_sse_error_handler(sse_data: str) -> NoReturn:
1724

1825
@contextmanager
1926
def handle_http_exceptions(
20-
status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn]
21-
| None = None,
27+
status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None,
2228
) -> Iterator[None]:
2329
"""Handles common HTTP exceptions for REST and JSON-RPC transports.
2430
2531
Args:
26-
status_error_handler: Optional handler for `httpx.HTTPStatusError`.
32+
status_error_handler: Optional handler for an HTTP status error.
2733
If provided, this handler should raise an appropriate domain-specific exception.
2834
If not provided, a default `A2AClientError` will be raised.
2935
"""
3036
try:
3137
yield
32-
except httpx.TimeoutException as e:
38+
except TIMEOUT_EXCEPTION as e:
3339
raise A2AClientTimeoutError('Client Request timed out') from e
34-
except httpx.HTTPStatusError as e:
40+
except HTTP_STATUS_ERROR as e:
3541
if status_error_handler:
3642
status_error_handler(e)
3743
raise A2AClientError(f'HTTP Error {e.response.status_code}: {e}') from e
38-
except httpx.RequestError as e:
44+
except REQUEST_ERROR as e:
3945
raise A2AClientError(f'Network communication error: {e}') from e
4046
except json.JSONDecodeError as e:
4147
raise A2AClientError(f'JSON Decode Error: {e}') from e
@@ -52,10 +58,9 @@ def get_http_args(context: ClientCallContext | None) -> dict[str, Any]:
5258

5359

5460
async def send_http_request(
55-
httpx_client: httpx.AsyncClient,
56-
request: httpx.Request,
57-
status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn]
58-
| None = None,
61+
httpx_client: AsyncClient,
62+
request: Request,
63+
status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None,
5964
) -> dict[str, Any]:
6065
"""Sends an HTTP request and parses the JSON response, handling common exceptions."""
6166
if httpx_client.is_closed:
@@ -70,7 +75,7 @@ async def send_http_request(
7075

7176

7277
async def _aiter_sse_lines(
73-
response: httpx.Response,
78+
response: Response,
7479
) -> AsyncGenerator[str, None]:
7580
"""Yields lines ended only by CRLF, LF or CR, unlike `aiter_lines()`.
7681
@@ -100,9 +105,9 @@ async def _aiter_sse_lines(
100105

101106

102107
async def parse_sse_stream(
103-
response: httpx.Response,
108+
response: Response,
104109
) -> AsyncGenerator[tuple[str, str], None]:
105-
"""Yields (event_name, data) from a streaming httpx.Response.
110+
"""Yields (event_name, data) from a streaming response.
106111
107112
Conforms to the W3C Server-Sent Events specification.
108113
"""
@@ -138,11 +143,10 @@ async def parse_sse_stream(
138143

139144

140145
async def send_http_stream_request(
141-
httpx_client: httpx.AsyncClient,
146+
httpx_client: AsyncClient,
142147
method: str,
143148
url: str,
144-
status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn]
145-
| None = None,
149+
status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None,
146150
sse_error_handler: Callable[[str], NoReturn] = _default_sse_error_handler,
147151
**kwargs: Any,
148152
) -> AsyncGenerator[str]:
@@ -167,7 +171,7 @@ async def send_http_stream_request(
167171
) as response:
168172
try:
169173
response.raise_for_status()
170-
except httpx.HTTPStatusError as e:
174+
except HTTP_STATUS_ERROR as e:
171175
# Read upfront streaming error content immediately, otherwise lower-level handlers
172176
# (e.g. response.json()) crash with 'ResponseNotRead' Access errors.
173177
await response.aread()
@@ -205,9 +209,12 @@ class _SSEEventSource:
205209
collision (see https://bugs.python.org/issue38559).
206210
"""
207211

212+
if TYPE_CHECKING:
213+
_request: Request
214+
208215
def __init__(
209216
self,
210-
client: httpx.AsyncClient,
217+
client: AsyncClient,
211218
method: str,
212219
url: str,
213220
**kwargs: Any,
@@ -222,9 +229,9 @@ def __init__(
222229
method, url, headers=headers, **kwargs
223230
)
224231
self._client = client
225-
self._response: httpx.Response | None = None
232+
self._response: Response | None = None
226233

227-
async def __aenter__(self) -> httpx.Response:
234+
async def __aenter__(self) -> Response:
228235
self._response = await self._client.send(self._request, stream=True)
229236
return self._response
230237

‎src/a2a/client/transports/jsonrpc.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
from typing import Any, NoReturn
66
from uuid import uuid4
77

8-
import httpx
9-
108
from google.protobuf import json_format
119
from jsonrpc.jsonrpc2 import JSONRPC20Request
1210

@@ -36,6 +34,7 @@
3634
Task,
3735
TaskPushNotificationConfig,
3836
)
37+
from a2a.utils._httpx_compat import AsyncClient
3938
from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP
4039
from a2a.utils.proto_utils import parse_lenient
4140
from a2a.utils.telemetry import SpanKind, trace_class
@@ -55,7 +54,7 @@ class JsonRpcTransport(ClientTransport):
5554

5655
def __init__(
5756
self,
58-
httpx_client: httpx.AsyncClient,
57+
httpx_client: AsyncClient,
5958
agent_card: AgentCard,
6059
url: str,
6160
is_shared_httpx: bool = False,

‎src/a2a/client/transports/rest.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
Task,
3737
TaskPushNotificationConfig,
3838
)
39+
from a2a.utils._httpx_compat import AsyncClient, HTTPStatusError, Request
3940
from a2a.utils.errors import A2A_REASON_TO_ERROR, MethodNotFoundError
4041
from a2a.utils.proto_utils import parse_lenient
4142
from a2a.utils.telemetry import SpanKind, trace_class
@@ -102,7 +103,7 @@ class RestTransport(ClientTransport):
102103

103104
def __init__(
104105
self,
105-
httpx_client: httpx.AsyncClient,
106+
httpx_client: AsyncClient,
106107
agent_card: AgentCard,
107108
url: str,
108109
is_shared_httpx: bool = False,
@@ -305,7 +306,7 @@ async def delete_task_push_notification_config(
305306
f'/pushNotificationConfigs/{_quote_id(request.id)}',
306307
request.tenant,
307308
)
308-
http_request = self.httpx_client.build_request(
309+
http_request: Request = self.httpx_client.build_request(
309310
'DELETE',
310311
f'{self.url}{path}',
311312
params=params,
@@ -370,7 +371,7 @@ def _get_path(self, base_path: str, tenant: str) -> str:
370371
"""Returns the full path, prepending the tenant if provided."""
371372
return f'/{tenant}{base_path}' if tenant else base_path
372373

373-
def _handle_http_error(self, e: httpx.HTTPStatusError) -> NoReturn:
374+
def _handle_http_error(self, e: HTTPStatusError) -> NoReturn:
374375
"""Handles HTTP status errors and raises the appropriate A2AError."""
375376
try:
376377
error_payload = e.response.json()
@@ -434,7 +435,7 @@ def _raise_in_band_error(self, sse_data: str) -> None:
434435
if isinstance(payload, dict) and 'error' in payload:
435436
self._handle_sse_error(sse_data)
436437

437-
async def _send_request(self, request: httpx.Request) -> dict[str, Any]:
438+
async def _send_request(self, request: Request) -> dict[str, Any]:
438439
return await send_http_request(
439440
self.httpx_client, request, self._handle_http_error
440441
)

0 commit comments

Comments
 (0)