Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/linter.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ jobs:
- name: Set up Python
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v6
with:
python-version-file: .python-version
python-version: '3.11'
- name: Install uv
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7
- name: Add uv to PATH
run: |
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
- name: Install dependencies
run: uv sync --locked
run: uv sync --locked --group httpx2
- name: Run Ruff Linter
id: ruff-lint
run: uv run ruff check --output-format=github
Expand Down
36 changes: 36 additions & 0 deletions .github/workflows/unit-tests.yml
Comment thread
Iwaniukooo11 marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,39 @@ jobs:

- name: Show coverage summary in log
run: uv run coverage report

# httpx2 testing - Running test on httpx2 for marked tests
httpx2:
name: Test with httpx2 (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest

if: github.repository == 'a2aproject/a2a-python'

strategy:
matrix:
Comment thread
Iwaniukooo11 marked this conversation as resolved.
Resolved
python-version: ['3.11', '3.12', '3.13', '3.14']
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6

- name: Install uv for Python ${{ matrix.python-version }}
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7
with:
python-version: ${{ matrix.python-version }}
- name: Add uv to PATH
run: |
echo "$HOME/.cargo/bin" >> $GITHUB_PATH

- name: Install dependencies
run: uv sync --locked --group httpx2

# httpx_lib silently falls back to httpx when httpx2 is missing, thus installing httpx2 is required
- name: Verify httpx2 is the installed flavor
run: |
uv run python -c "
from a2a.utils._httpx_compat import httpx_lib
assert httpx_lib.__name__ == 'httpx2', httpx_lib.__name__
"

- name: Run tests
run: uv run pytest -m httpx2
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ addopts = "-ra --strict-markers --dist loadgroup"
markers = [
"asyncio: mark a test as a coroutine that should be run by pytest-asyncio",
"xdist_group: mark a test to run in a specific sequential group for isolation",
"httpx2: mark a test whose behavior depends on the installed HTTP client",
]
filterwarnings = [
# SQLAlchemy warning about duplicate class registration - this is a known limitation
Expand All @@ -105,6 +106,7 @@ vcs = "git"
style = "pep440"

[dependency-groups]
httpx2 = ["httpx2>=2.0.0,<3 ; python_version >= '3.11'"]
dev = [
"fastapi>=0.115.2",
"PyJWT>=2.0.0",
Expand Down
16 changes: 10 additions & 6 deletions src/a2a/client/card_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@
from collections.abc import Callable
from typing import Any

import httpx

from google.protobuf.json_format import ParseDict, ParseError

from a2a.client.errors import AgentCardResolutionError
from a2a.types.a2a_pb2 import (
AgentCard,
)
from a2a.utils._httpx_compat import (
HTTP_STATUS_ERROR,
REQUEST_ERROR,
AsyncClient,
)
from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH


Expand Down Expand Up @@ -133,14 +136,15 @@ class A2ACardResolver:

def __init__(
self,
httpx_client: httpx.AsyncClient,
httpx_client: AsyncClient,
base_url: str,
agent_card_path: str = AGENT_CARD_WELL_KNOWN_PATH,
) -> None:
"""Initializes the A2ACardResolver.

Args:
httpx_client: An async HTTP client instance (e.g., httpx.AsyncClient).
httpx_client: An async HTTP client instance (`httpx.AsyncClient`
or `httpx2.AsyncClient`).
base_url: The base URL of the agent's host.
agent_card_path: The path to the agent card endpoint, relative to the base URL.
"""
Expand Down Expand Up @@ -200,7 +204,7 @@ async def get_agent_card(
agent_card = parse_agent_card(agent_card_data)
if signature_verifier:
signature_verifier(agent_card)
except httpx.HTTPStatusError as e:
except HTTP_STATUS_ERROR as e:
raise AgentCardResolutionError(
f'Failed to fetch agent card from {target_url} (HTTP {e.response.status_code}): {e}',
status_code=e.response.status_code,
Expand All @@ -209,7 +213,7 @@ async def get_agent_card(
raise AgentCardResolutionError(
f'Failed to parse JSON for agent card from {target_url}: {e}'
) from e
except httpx.RequestError as e:
except REQUEST_ERROR as e:
raise AgentCardResolutionError(
f'Network communication error fetching agent card from {target_url}: {e}',
) from e
Expand Down
5 changes: 2 additions & 3 deletions src/a2a/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
from types import TracebackType
from typing import Any

import httpx

from pydantic import BaseModel, Field
from typing_extensions import Self

Expand All @@ -31,6 +29,7 @@
Task,
TaskPushNotificationConfig,
)
from a2a.utils._httpx_compat import AsyncClient


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

httpx_client: httpx.AsyncClient | None = None
httpx_client: AsyncClient | None = None
"""Http client to use to connect to agent."""

grpc_channel_factory: Callable[[str], Channel] | None = None
Expand Down
3 changes: 2 additions & 1 deletion src/a2a/client/client_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,19 @@

if TYPE_CHECKING:
from a2a.client.interceptors import ClientCallInterceptor
from a2a.utils._httpx_compat import AsyncClient


try:
from a2a.client.transports.grpc import GrpcTransport
except ImportError:
GrpcTransport = None # type: ignore # pyright: ignore

Check warning on line 42 in src/a2a/client/client_factory.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

ty (unused-type-ignore-comment)

src/a2a/client/client_factory.py:42:27: unused-type-ignore-comment: Unused blanket `type: ignore` directive help: Remove the unused suppression comment


try:
from a2a.compat.v0_3.grpc_transport import CompatGrpcTransport
except ImportError:
CompatGrpcTransport = None # type: ignore # pyright: ignore

Check warning on line 48 in src/a2a/client/client_factory.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

ty (unused-type-ignore-comment)

src/a2a/client/client_factory.py:48:33: unused-type-ignore-comment: Unused blanket `type: ignore` directive help: Remove the unused suppression comment

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -96,7 +97,7 @@
self._registry: dict[str, TransportProducer] = {}
self._register_defaults(config.supported_protocol_bindings)

def _resolve_http_client(self) -> tuple[httpx.AsyncClient, bool]:
def _resolve_http_client(self) -> tuple[AsyncClient, bool]:
"""Returns an HTTP client and whether it is shared across clients."""
if self._config.httpx_client:
return self._config.httpx_client, True
Expand Down
53 changes: 30 additions & 23 deletions src/a2a/client/transports/http_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@

from collections.abc import AsyncGenerator, Callable, Iterator
from contextlib import contextmanager
from typing import Any, NoReturn

import httpx
from typing import TYPE_CHECKING, Any, NoReturn

from a2a.client.client import ClientCallContext
from a2a.client.errors import A2AClientError, A2AClientTimeoutError
from a2a.utils._httpx_compat import (
HTTP_STATUS_ERROR,
REQUEST_ERROR,
TIMEOUT_EXCEPTION,
AsyncClient,
HTTPStatusError,
Request,
Response,
)


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

@contextmanager
def handle_http_exceptions(
status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn]
| None = None,
status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None,
) -> Iterator[None]:
"""Handles common HTTP exceptions for REST and JSON-RPC transports.

Args:
status_error_handler: Optional handler for `httpx.HTTPStatusError`.
status_error_handler: Optional handler for an HTTP status error.
If provided, this handler should raise an appropriate domain-specific exception.
If not provided, a default `A2AClientError` will be raised.
"""
try:
yield
except httpx.TimeoutException as e:
except TIMEOUT_EXCEPTION as e:
raise A2AClientTimeoutError('Client Request timed out') from e
except httpx.HTTPStatusError as e:
except HTTP_STATUS_ERROR as e:
if status_error_handler:
status_error_handler(e)
raise A2AClientError(f'HTTP Error {e.response.status_code}: {e}') from e
except httpx.RequestError as e:
except REQUEST_ERROR as e:
raise A2AClientError(f'Network communication error: {e}') from e
except json.JSONDecodeError as e:
raise A2AClientError(f'JSON Decode Error: {e}') from e
Expand All @@ -52,10 +58,9 @@ def get_http_args(context: ClientCallContext | None) -> dict[str, Any]:


async def send_http_request(
httpx_client: httpx.AsyncClient,
request: httpx.Request,
status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn]
| None = None,
httpx_client: AsyncClient,
request: Request,
status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None,
) -> dict[str, Any]:
"""Sends an HTTP request and parses the JSON response, handling common exceptions."""
if httpx_client.is_closed:
Expand All @@ -70,7 +75,7 @@ async def send_http_request(


async def _aiter_sse_lines(
response: httpx.Response,
response: Response,
) -> AsyncGenerator[str, None]:
"""Yields lines ended only by CRLF, LF or CR, unlike `aiter_lines()`.

Expand Down Expand Up @@ -100,9 +105,9 @@ async def _aiter_sse_lines(


async def parse_sse_stream(
response: httpx.Response,
response: Response,
) -> AsyncGenerator[tuple[str, str], None]:
"""Yields (event_name, data) from a streaming httpx.Response.
"""Yields (event_name, data) from a streaming response.

Conforms to the W3C Server-Sent Events specification.
"""
Expand Down Expand Up @@ -138,11 +143,10 @@ async def parse_sse_stream(


async def send_http_stream_request(
httpx_client: httpx.AsyncClient,
httpx_client: AsyncClient,
method: str,
url: str,
status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn]
| None = None,
status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None,
sse_error_handler: Callable[[str], NoReturn] = _default_sse_error_handler,
**kwargs: Any,
) -> AsyncGenerator[str]:
Expand All @@ -167,7 +171,7 @@ async def send_http_stream_request(
) as response:
try:
response.raise_for_status()
except httpx.HTTPStatusError as e:
except HTTP_STATUS_ERROR as e:
# Read upfront streaming error content immediately, otherwise lower-level handlers
# (e.g. response.json()) crash with 'ResponseNotRead' Access errors.
await response.aread()
Expand Down Expand Up @@ -205,9 +209,12 @@ class _SSEEventSource:
collision (see https://bugs.python.org/issue38559).
"""

if TYPE_CHECKING:
_request: Request

def __init__(
self,
client: httpx.AsyncClient,
client: AsyncClient,
method: str,
url: str,
**kwargs: Any,
Expand All @@ -222,9 +229,9 @@ def __init__(
method, url, headers=headers, **kwargs
)
self._client = client
self._response: httpx.Response | None = None
self._response: Response | None = None

async def __aenter__(self) -> httpx.Response:
async def __aenter__(self) -> Response:
self._response = await self._client.send(self._request, stream=True)
return self._response

Expand Down
5 changes: 2 additions & 3 deletions src/a2a/client/transports/jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
from typing import Any, NoReturn
from uuid import uuid4

import httpx

from google.protobuf import json_format
from jsonrpc.jsonrpc2 import JSONRPC20Request

Expand All @@ -14,29 +12,30 @@
from a2a.client.errors import A2AClientError
from a2a.client.transports.base import ClientTransport
from a2a.client.transports.http_helpers import (
get_http_args,
send_http_request,
send_http_stream_request,
)
from a2a.types.a2a_pb2 import (
AgentCard,
CancelTaskRequest,
DeleteTaskPushNotificationConfigRequest,
GetExtendedAgentCardRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
ListTaskPushNotificationConfigsRequest,
ListTaskPushNotificationConfigsResponse,
ListTasksRequest,
ListTasksResponse,
SendMessageRequest,
SendMessageResponse,
StreamResponse,
SubscribeToTaskRequest,
Task,
TaskPushNotificationConfig,
)
from a2a.utils._httpx_compat import AsyncClient
from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP

Check notice on line 38 in src/a2a/client/transports/jsonrpc.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Copy/pasted code

see src/a2a/client/transports/rest.py (17-39)
from a2a.utils.proto_utils import parse_lenient
from a2a.utils.telemetry import SpanKind, trace_class

Expand All @@ -55,7 +54,7 @@

def __init__(
self,
httpx_client: httpx.AsyncClient,
httpx_client: AsyncClient,
agent_card: AgentCard,
url: str,
is_shared_httpx: bool = False,
Expand Down
9 changes: 5 additions & 4 deletions src/a2a/client/transports/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,29 @@
from a2a.client.transports.base import ClientTransport
from a2a.client.transports.http_helpers import (
get_http_args,
handle_http_exceptions,
send_http_request,
send_http_stream_request,
)
from a2a.types.a2a_pb2 import (
AgentCard,
CancelTaskRequest,
DeleteTaskPushNotificationConfigRequest,
GetExtendedAgentCardRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
ListTaskPushNotificationConfigsRequest,
ListTaskPushNotificationConfigsResponse,
ListTasksRequest,
ListTasksResponse,
SendMessageRequest,
SendMessageResponse,
StreamResponse,
SubscribeToTaskRequest,
Task,
TaskPushNotificationConfig,
)
from a2a.utils._httpx_compat import AsyncClient, HTTPStatusError, Request

Check notice on line 39 in src/a2a/client/transports/rest.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Copy/pasted code

see src/a2a/client/transports/jsonrpc.py (15-38)
from a2a.utils.errors import A2A_REASON_TO_ERROR, MethodNotFoundError
from a2a.utils.proto_utils import parse_lenient
from a2a.utils.telemetry import SpanKind, trace_class
Expand Down Expand Up @@ -102,7 +103,7 @@

def __init__(
self,
httpx_client: httpx.AsyncClient,
httpx_client: AsyncClient,
agent_card: AgentCard,
url: str,
is_shared_httpx: bool = False,
Expand Down Expand Up @@ -305,7 +306,7 @@
f'/pushNotificationConfigs/{_quote_id(request.id)}',
request.tenant,
)
http_request = self.httpx_client.build_request(
http_request: Request = self.httpx_client.build_request(
'DELETE',
f'{self.url}{path}',
params=params,
Expand Down Expand Up @@ -370,7 +371,7 @@
"""Returns the full path, prepending the tenant if provided."""
return f'/{tenant}{base_path}' if tenant else base_path

def _handle_http_error(self, e: httpx.HTTPStatusError) -> NoReturn:
def _handle_http_error(self, e: HTTPStatusError) -> NoReturn:
"""Handles HTTP status errors and raises the appropriate A2AError."""
try:
error_payload = e.response.json()
Expand Down Expand Up @@ -434,7 +435,7 @@
if isinstance(payload, dict) and 'error' in payload:
self._handle_sse_error(sse_data)

async def _send_request(self, request: httpx.Request) -> dict[str, Any]:
async def _send_request(self, request: Request) -> dict[str, Any]:
return await send_http_request(
self.httpx_client, request, self._handle_http_error
)
Expand Down
Loading
Loading