-
Notifications
You must be signed in to change notification settings - Fork 419
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 all commits
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
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,70 @@ | ||
| import argparse | ||
| import asyncio | ||
|
|
||
| import grpc | ||
| import httpx | ||
|
|
||
| from a2a.client import A2ACardResolver, ClientConfig, 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' | ||
| ) | ||
| parser.add_argument( | ||
| '--transport', | ||
| default=None, | ||
| help='Preferred transport (JSONRPC, HTTP+JSON, GRPC)', | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| config = ClientConfig() | ||
| if args.transport: | ||
| config.supported_protocol_bindings = [args.transport] | ||
| if args.transport == 'GRPC': | ||
| config.grpc_channel_factory = grpc.aio.insecure_channel | ||
|
|
||
| print( | ||
| f'Connecting to {args.url} (preferred transport: {args.transport or "Any"})' | ||
| ) | ||
|
|
||
| async with httpx.AsyncClient() as httpx_client: | ||
| resolver = A2ACardResolver(httpx_client, args.url) | ||
| card = await resolver.get_agent_card() | ||
| print('\n✓ Agent Card Found:') | ||
| print(f' Name: {card.name}') | ||
|
|
||
| text_client = await create_text_client(card, client_config=config) | ||
|
|
||
| actual_transport = getattr( | ||
| text_client.client, '_transport', text_client.client | ||
| ) | ||
| print(f' Picked Transport: {actual_transport.__class__.__name__}') | ||
|
|
||
| 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,114 @@ | ||
| import uuid | ||
|
|
||
| from types import TracebackType | ||
|
|
||
| from typing_extensions import Self | ||
|
|
||
| from a2a.client.client import Client, ClientCallContext | ||
| from a2a.types import Message, Part, Role, SendMessageRequest, TaskState | ||
| from a2a.utils import get_artifact_text, get_message_text | ||
|
|
||
|
|
||
| _TERMINAL_STATES: frozenset[TaskState] = frozenset( | ||
| { | ||
| TaskState.TASK_STATE_COMPLETED, | ||
| TaskState.TASK_STATE_FAILED, | ||
| TaskState.TASK_STATE_CANCELED, | ||
| TaskState.TASK_STATE_REJECTED, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| 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. | ||
| Maintains session state (context_id, task_id) automatically across calls. | ||
| For full Client API access, use the underlying client directly via | ||
| the `client` property. | ||
| """ | ||
|
|
||
| def __init__(self, client: Client): | ||
| self._client = client | ||
| self._context_id: str = str(uuid.uuid4()) | ||
| self._task_id: str | None = None | ||
|
|
||
| async def __aenter__(self) -> Self: | ||
| """Enters the async context manager.""" | ||
| return self | ||
|
|
||
| async def __aexit__( | ||
| self, | ||
| exc_type: type[BaseException] | None, | ||
| exc_val: BaseException | None, | ||
| exc_tb: TracebackType | None, | ||
| ) -> None: | ||
| """Exits the async context manager and closes the client.""" | ||
| await self.close() | ||
|
|
||
| @property | ||
| def client(self) -> Client: | ||
| """Returns the underlying Client instance for full API access.""" | ||
| return self._client | ||
|
|
||
| def reset_session(self) -> None: | ||
| """Starts a new session by generating a fresh context ID and clearing the task ID.""" | ||
| self._context_id = str(uuid.uuid4()) | ||
| self._task_id = None | ||
|
|
||
| async def send_text_message( | ||
| self, | ||
| text: str, | ||
| *, | ||
| delimiter: str = ' ', | ||
| context: ClientCallContext | None = None, | ||
| ) -> str: | ||
| """Sends a text message and returns the aggregated text response. | ||
|
|
||
| Session state (context_id, task_id) is managed automatically across | ||
| calls. Use reset_session() to start a new conversation. | ||
|
|
||
| Args: | ||
| text: The plain-text message to send. | ||
| delimiter: String used to join response parts. Defaults to a | ||
| single space. Use '' for token-streamed responses or a | ||
| newline for paragraph-separated chunks. | ||
| context: Optional call-level context. | ||
| """ | ||
| request = SendMessageRequest( | ||
| message=Message( | ||
| role=Role.ROLE_USER, | ||
| message_id=str(uuid.uuid4()), | ||
| context_id=self._context_id, | ||
| task_id=self._task_id, | ||
| parts=[Part(text=text)], | ||
| ) | ||
| ) | ||
|
|
||
| response_parts: list[str] = [] | ||
|
|
||
| async for event in self._client.send_message(request, context=context): | ||
| if event.HasField('task'): | ||
| self._task_id = event.task.id | ||
| elif event.HasField('message'): | ||
| response_parts.append(get_message_text(event.message)) | ||
| elif event.HasField('status_update'): | ||
| if not self._task_id and event.status_update.task_id: | ||
| self._task_id = event.status_update.task_id | ||
| if event.status_update.status.state in _TERMINAL_STATES: | ||
| self._task_id = None | ||
| if event.status_update.status.HasField('message'): | ||
| response_parts.append( | ||
| get_message_text(event.status_update.status.message) | ||
| ) | ||
| elif event.HasField('artifact_update'): | ||
| response_parts.append( | ||
| get_artifact_text(event.artifact_update.artifact) | ||
| ) | ||
|
sokoliva marked this conversation as resolved.
|
||
|
|
||
| return delimiter.join(response_parts) | ||
|
|
||
| async def close(self) -> None: | ||
| """Closes the underlying client.""" | ||
| await self._client.close() | ||
Oops, something went wrong.
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.