-
Notifications
You must be signed in to change notification settings - Fork 423
feat: add a TextClient class for a simplified text-based communication
#963
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
eb30ac3
feat: add a `TextClient` class for a simplified text-based communication
sokoliva 95b224e
Add README.md, task_id persistence
sokoliva 03366d9
fix
sokoliva f75354a
Merge branch '1.0-dev' of https://github.com/a2aproject/a2a-python in…
sokoliva 82ac284
few small fixes
sokoliva File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import argparse | ||
| import asyncio | ||
|
|
||
| import grpc | ||
| import httpx | ||
|
|
||
| from a2a.client import A2ACardResolver, create_text_client | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| """Run the simple A2A terminal client using TextClient.""" | ||
| parser = argparse.ArgumentParser(description='A2A Simple Text Client') | ||
| parser.add_argument( | ||
| '--url', default='http://127.0.0.1:41241', help='Agent base URL' | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| print(f'Connecting to {args.url}') | ||
|
|
||
| async with httpx.AsyncClient() as httpx_client: | ||
| resolver = A2ACardResolver(httpx_client, args.url) | ||
| card = await resolver.get_agent_card() | ||
| print(f'\n✓ Agent Card Found: {card.name}') | ||
|
|
||
| text_client = await create_text_client(card) | ||
|
|
||
| print('\nConnected! Send a message or type /quit to exit.') | ||
|
|
||
| while True: | ||
| try: | ||
| loop = asyncio.get_running_loop() | ||
| user_input = await loop.run_in_executor(None, input, 'You: ') | ||
| except KeyboardInterrupt: | ||
| break | ||
|
|
||
| if user_input.lower() in ('/quit', '/exit'): | ||
| break | ||
| if not user_input.strip(): | ||
| continue | ||
|
|
||
| try: | ||
| response = await text_client.send_text_message(user_input) | ||
| print(f'Agent: {response}') | ||
| except (httpx.RequestError, grpc.RpcError) as e: | ||
| print(f'Error communicating with agent: {e}') | ||
|
|
||
| await text_client.close() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| asyncio.run(main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import uuid | ||
|
|
||
| from a2a.client.client import Client, ClientCallContext | ||
| from a2a.types import Message, Part, Role, SendMessageRequest | ||
|
|
||
|
|
||
| class TextClient: | ||
|
sokoliva marked this conversation as resolved.
|
||
| """A facade around Client that simplifies text-based communication. | ||
|
|
||
| Wraps an underlying Client instance and exposes a simplified interface | ||
| for sending plain-text messages and receiving aggregated text responses. | ||
| For full Client API access, use the underlying client directly via | ||
| the `client` property. | ||
| """ | ||
|
|
||
| def __init__(self, client: Client): | ||
| self._client = client | ||
|
|
||
| @property | ||
| def client(self) -> Client: | ||
| """Returns the underlying Client instance for full API access.""" | ||
| return self._client | ||
|
|
||
| async def send_text_message( | ||
| self, | ||
| text: str, | ||
| *, | ||
| context: ClientCallContext | None = None, | ||
| ) -> str: | ||
| """Sends a text message and returns the aggregated text response.""" | ||
| request = SendMessageRequest( | ||
| message=Message( | ||
| role=Role.ROLE_USER, | ||
| message_id=str(uuid.uuid4()), | ||
| parts=[Part(text=text)], | ||
| ) | ||
| ) | ||
|
|
||
| response_parts: list[str] = [] | ||
|
|
||
| async for event in self._client.send_message(request, context=context): | ||
| if event.HasField('message'): | ||
| response_parts.extend( | ||
| part.text for part in event.message.parts if part.text | ||
| ) | ||
| elif event.HasField('status_update'): | ||
| if event.status_update.status.HasField('message'): | ||
| response_parts.extend( | ||
| part.text | ||
| for part in event.status_update.status.message.parts | ||
| if part.text | ||
| ) | ||
| elif event.HasField('artifact_update'): | ||
| response_parts.extend( | ||
| part.text | ||
| for part in event.artifact_update.artifact.parts | ||
| if part.text | ||
| ) | ||
|
sokoliva marked this conversation as resolved.
|
||
|
|
||
| return ' '.join(response_parts) | ||
|
sokoliva marked this conversation as resolved.
Outdated
|
||
|
|
||
| async def close(self) -> None: | ||
| """Closes the underlying client.""" | ||
| await self._client.close() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| from unittest.mock import AsyncMock | ||
|
|
||
| import pytest | ||
|
|
||
| from a2a.client import ( | ||
| Client, | ||
| ClientConfig, | ||
| ClientCallContext, | ||
| create_text_client, | ||
| minimal_agent_card, | ||
| TextClient, | ||
| ) | ||
| from a2a.types import Part, StreamResponse | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_client() -> AsyncMock: | ||
| return AsyncMock(spec=Client) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def text_client(mock_client: AsyncMock) -> TextClient: | ||
| return TextClient(mock_client) | ||
|
|
||
|
|
||
| def test_client_property( | ||
| text_client: TextClient, mock_client: AsyncMock | ||
| ) -> None: | ||
| assert text_client.client is mock_client | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_create_client_and_wrap() -> None: | ||
| # Create a minimal card | ||
| card = minimal_agent_card(url='http://test.com', transports=['JSONRPC']) | ||
|
|
||
| config = ClientConfig(supported_protocol_bindings=['JSONRPC']) | ||
|
|
||
| text_client = await create_text_client(card, client_config=config) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hi, when I do text_client = await create_text_client(
agent=SERVER_URL,
client_config=ClientConfig(streaming=False, supported_protocol_bindings="JSONRPC")
)I get |
||
|
|
||
| assert isinstance(text_client, TextClient) | ||
| assert isinstance(text_client.client, Client) | ||
|
|
||
| # Clean up | ||
| await text_client.close() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_send_text_message( | ||
| text_client: TextClient, mock_client: AsyncMock | ||
| ) -> None: | ||
| async def create_stream(*args, **kwargs): | ||
| # Event 0: task (ignored) | ||
| resp0 = StreamResponse() | ||
| resp0.task.id = 'task-1' | ||
| yield resp0 | ||
|
|
||
| # Event 1: direct message | ||
| resp1 = StreamResponse() | ||
| resp1.message.parts.append(Part(text='Hello')) | ||
| yield resp1 | ||
|
|
||
| # Event 2: status update without message | ||
| resp2 = StreamResponse() | ||
| resp2.status_update.status.state = 1 | ||
| yield resp2 | ||
|
|
||
| # Event 3: status update with message | ||
| resp3 = StreamResponse() | ||
| resp3.status_update.status.message.parts.append(Part(text='Processing')) | ||
| yield resp3 | ||
|
|
||
| # Event 4: artifact update | ||
| resp4 = StreamResponse() | ||
| resp4.artifact_update.artifact.parts.append(Part(text='World!')) | ||
| yield resp4 | ||
|
|
||
| mock_client.send_message.return_value = create_stream() | ||
|
|
||
| response = await text_client.send_text_message('Hi') | ||
|
|
||
| assert response == 'Hello Processing World!' | ||
| mock_client.send_message.assert_called_once() | ||
| # Verify request construction | ||
| args, _ = mock_client.send_message.call_args | ||
| request = args[0] | ||
| assert request.message.parts[0].text == 'Hi' | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_send_text_message_forwards_context( | ||
| text_client: TextClient, mock_client: AsyncMock | ||
| ) -> None: | ||
|
|
||
| async def empty_stream(*args, **kwargs): | ||
| return | ||
| yield | ||
|
|
||
| mock_client.send_message.return_value = empty_stream() | ||
| context = ClientCallContext() | ||
|
|
||
| await text_client.send_text_message('Hi', context=context) | ||
|
|
||
| _, kwargs = mock_client.send_message.call_args | ||
| assert kwargs['context'] is context | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_close(text_client: TextClient, mock_client: AsyncMock) -> None: | ||
| await text_client.close() | ||
| mock_client.close.assert_awaited_once() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
agentword is too broad. Can we do ?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
agentcan also be the base URL of the agent so renaming it toagent_cardcould be misleading. WDYT?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You are right. I just noticed optional
str. My bad! Let's keep it as it but add 2 example in doc-string.