A2A/docs/tutorials/python/6-interact-with-server.md

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

96 lines
4.4 KiB
Markdown
Raw Permalink Normal View History

# 6. Interacting with the Server
With the Helloworld A2A server running, let's send some requests to it. The SDK includes a client (`A2AClient`) that simplifies these interactions.
## The Helloworld Test Client
The `test_client.py` script demonstrates how to:
1. Fetch the Agent Card from the server.
2. Create an `A2AClient` instance.
3. Send both non-streaming (`message/send`) and streaming (`message/stream`) requests.
Open a **new terminal window**, activate your virtual environment, and navigate to the `a2a-samples` directory.
Activate virtual environment (Be sure to do this in the same directory where you created the virtual environment):
=== "Mac/Linux"
```sh
source .venv/bin/activate
```
=== "Windows"
```powershell
.venv\Scripts\activate
```
Run the test client:
```bash
# from the a2a-samples directory
python samples/python/agents/helloworld/test_client.py
```
## Understanding the Client Code
Let's look at key parts of `test_client.py`:
1. **Fetching the Agent Card & Initializing the Client**:
```python { .no-copy }
2025-06-23 21:34:48 +02:00
--8<-- "https://raw.githubusercontent.com/a2aproject/a2a-samples/refs/heads/main/samples/python/agents/helloworld/test_client.py:A2ACardResolver"
```
The `A2ACardResolver` class is a convenience. It first fetches the `AgentCard` from the server's `/.well-known/agent-card.json` endpoint (based on the provided base URL) and then initializes the client with it.
2. **Sending a Non-Streaming Message (`send_message`)**:
```python { .no-copy }
2025-06-23 21:34:48 +02:00
--8<-- "https://raw.githubusercontent.com/a2aproject/a2a-samples/refs/heads/main/samples/python/agents/helloworld/test_client.py:send_message"
```
- The `send_message_payload` constructs the data for `MessageSendParams`.
- This is wrapped in a `SendMessageRequest`.
- It includes a `message` object with the `role` set to "user" and the content in `parts`.
- The Helloworld agent's `execute` method will enqueue a single "Hello World" message. The `DefaultRequestHandler` will retrieve this and send it as the response.
- The `response` will be a `SendMessageResponse` object, which contains either a `SendMessageSuccessResponse` (with the agent's `Message` as the result) or a `JSONRPCErrorResponse`.
3. **Handling Task IDs (Illustrative Note for Helloworld)**:
The Helloworld client (`test_client.py`) doesn't attempt `get_task` or `cancel_task` directly because the simple Helloworld agent's `execute` method, when called via `message/send`, results in the `DefaultRequestHandler` returning a direct `Message` response rather than a `Task` object. More complex agents that explicitly manage tasks (like the LangGraph example) would return a `Task` object from `message/send`, and its `id` could then be used for `get_task` or `cancel_task`.
4. **Sending a Streaming Message (`send_message_streaming`)**:
```python { .no-copy }
2025-06-23 21:34:48 +02:00
--8<-- "https://raw.githubusercontent.com/a2aproject/a2a-samples/refs/heads/main/samples/python/agents/helloworld/test_client.py:send_message_streaming"
```
- This method calls the agent's `message/stream` endpoint. The `DefaultRequestHandler` will invoke the `HelloWorldAgentExecutor.execute` method.
- The `execute` method enqueues one "Hello World" message, and then the event queue is closed.
- The client will receive this single message as one `SendStreamingMessageResponse` event, and then the stream will terminate.
- The `stream_response` is an `AsyncGenerator`.
## Expected Output
When you run `test_client.py`, you'll see JSON outputs for:
- The non-streaming response (a single "Hello World" message).
- The streaming response (a single "Hello World" message as one chunk, after which the stream ends).
The `id` fields in the output will vary with each run.
```console { .no-copy }
// Non-streaming response
docs(spec): Update inconsistencies in documentation for 1.0 Spec (#1466) In the future, we should probably explore refactoring the docs set to avoid these becoming out of sync going forward This pull request updates the project documentation to align with the v1.0 Agent2Agent (A2A) Protocol Specification defined in specification/a2a.proto. It ensures that all conceptual guides, summaries, and tutorials reflect the current normative definitions, RPC method names, and wire formats. Summary of Changes 1. RPC Method Naming Updates Standardized all method references to use the v1.0 PascalCase naming convention: * `message/send` → `SendMessage` * `message/stream` → `SendStreamingMessage` * `tasks/get` → `GetTask` * `tasks/list` → `ListTasks` * `tasks/cancel` → `CancelTask` * `tasks/pushNotificationConfig/set` → `CreateTaskPushNotificationConfig` * `tasks/resubscribe` → `SubscribeToTask` * `agent/getAuthenticatedExtendedCard` → `GetExtendedAgentCard` 2. JSON Example & Wire Format Corrections Updated examples across all "Topic" files and the Python Quickstart to match v1.0 breaking changes: * Removed `kind` discriminators: Examples for Message, Task, Part, and StreamResponse now use member-based polymorphism (e.g., {"text": "..."} instead of {"kind": "text", "text": "..."}). * Enum Standardization: Changed role and state enums from kebab-case/lowercase to SCREAMING_SNAKE_CASE with type prefixes (e.g., `"ROLE_USER"`, `"TASK_STATE_COMPLETED"`). * Response Wrapping: Updated examples to reflect that `SendMessage` and `SendStreamingMessage` return a unified response object where the message or task is nested within the result. 3. LLM Context (`docs/llms.txt`) * Completely refreshed the protocol summary and RPC method list to ensure LLM-based tools (like Gemini CLI) have an accurate representation of the v1.0 API surface and error codes. 4. Link & Anchor Maintenance * Updated internal documentation links and spans to point to the correct sections in the specification.md (e.g., correcting the anchor for GetExtendedAgentCard). Why this is needed The v1.0 release introduced significant structural improvements for ProtoJSON compliance and architectural consistency. Documentation examples were previously showing v0.3.0 patterns which would cause integration errors for developers using the latest SDKs.
2026-02-10 11:45:49 -06:00
{"jsonrpc":"2.0","id":"xxxxxxxx","result":{"message":{"role":"ROLE_AGENT","parts":[{"text":"Hello World"}],"messageId":"yyyyyyyy"}}}
// Streaming response (one chunk)
docs(spec): Update inconsistencies in documentation for 1.0 Spec (#1466) In the future, we should probably explore refactoring the docs set to avoid these becoming out of sync going forward This pull request updates the project documentation to align with the v1.0 Agent2Agent (A2A) Protocol Specification defined in specification/a2a.proto. It ensures that all conceptual guides, summaries, and tutorials reflect the current normative definitions, RPC method names, and wire formats. Summary of Changes 1. RPC Method Naming Updates Standardized all method references to use the v1.0 PascalCase naming convention: * `message/send` → `SendMessage` * `message/stream` → `SendStreamingMessage` * `tasks/get` → `GetTask` * `tasks/list` → `ListTasks` * `tasks/cancel` → `CancelTask` * `tasks/pushNotificationConfig/set` → `CreateTaskPushNotificationConfig` * `tasks/resubscribe` → `SubscribeToTask` * `agent/getAuthenticatedExtendedCard` → `GetExtendedAgentCard` 2. JSON Example & Wire Format Corrections Updated examples across all "Topic" files and the Python Quickstart to match v1.0 breaking changes: * Removed `kind` discriminators: Examples for Message, Task, Part, and StreamResponse now use member-based polymorphism (e.g., {"text": "..."} instead of {"kind": "text", "text": "..."}). * Enum Standardization: Changed role and state enums from kebab-case/lowercase to SCREAMING_SNAKE_CASE with type prefixes (e.g., `"ROLE_USER"`, `"TASK_STATE_COMPLETED"`). * Response Wrapping: Updated examples to reflect that `SendMessage` and `SendStreamingMessage` return a unified response object where the message or task is nested within the result. 3. LLM Context (`docs/llms.txt`) * Completely refreshed the protocol summary and RPC method list to ensure LLM-based tools (like Gemini CLI) have an accurate representation of the v1.0 API surface and error codes. 4. Link & Anchor Maintenance * Updated internal documentation links and spans to point to the correct sections in the specification.md (e.g., correcting the anchor for GetExtendedAgentCard). Why this is needed The v1.0 release introduced significant structural improvements for ProtoJSON compliance and architectural consistency. Documentation examples were previously showing v0.3.0 patterns which would cause integration errors for developers using the latest SDKs.
2026-02-10 11:45:49 -06:00
{"jsonrpc":"2.0","id":"zzzzzzzz","result":{"message":{"role":"ROLE_AGENT","parts":[{"text":"Hello World"}],"messageId":"wwwwwwww"}}}
```
_(Actual IDs like `xxxxxxxx`, `yyyyyyyy`, `zzzzzzzz`, `wwwwwwww` will be different UUIDs/request IDs)_
This confirms your server is correctly handling basic A2A interactions with the updated SDK structure!
Now you can shut down the server by typing Ctrl+C in the terminal window where `__main__.py` is running.