### Install a2a-sdk Source: https://a2a-protocol.org/latest/sdk/python/api/index.html Use this command to install the a2a-sdk Python package. ```bash pip install a2a-sdk ``` -------------------------------- ### Install a2a-sdk Source: https://a2a-protocol.org/latest/sdk/python/api/_sources/index.rst.txt Install the a2a-sdk package using pip. ```sh pip install a2a-sdk ``` -------------------------------- ### Protocol Binding Versioning Example Source: https://a2a-protocol.org/latest/specification This example illustrates how to version a protocol binding URI when introducing breaking changes. A new URI must be used for incompatible versions. ```text https://example.com/bindings/websocket/v1 → https://example.com/bindings/websocket/v2 ``` -------------------------------- ### Verify A2A SDK Installation Source: https://a2a-protocol.org/latest/tutorials/python/2-setup Verify that the A2A SDK has been installed correctly by importing the 'a2a' package in a Python interpreter. A success message indicates a correct setup. ```python python -c "import a2a; print('A2A SDK imported successfully')" ``` -------------------------------- ### Run Helloworld Server Source: https://a2a-protocol.org/latest/tutorials/python/5-start-server Execute this command from the a2a-samples directory to start the Helloworld server. Ensure your virtual environment is activated. ```bash # from the a2a-samples directory python samples/python/agents/helloworld/__main__.py ``` -------------------------------- ### Install A2A Python SDK Dependencies Source: https://a2a-protocol.org/latest/tutorials/python/2-setup Install the A2A Python SDK and its required dependencies using pip. Ensure your virtual environment is activated before running this command. ```bash pip install -r samples/python/requirements.txt ``` -------------------------------- ### Start A2A Reimbursement Agent Server Source: https://a2a-protocol.org/latest/topics/extensions This Python script demonstrates how to initialize and run an A2A server for a reimbursement agent using the a2a.server SDK. It configures agent capabilities, skills, and request handling, then starts the server with uvicorn. Ensure necessary environment variables like GEMINI_API_KEY are set. ```python import logging import os import sys import click import uvicorn from a2a.server.apps import A2AStarletteApplication from a2a.server.request_handlers import DefaultRequestHandler from a2a.server.tasks import InMemoryTaskStore from a2a.types import AgentCapabilities, AgentCard, AgentSkill from agent import ReimbursementAgent from agent_executor import ReimbursementAgentExecutor from dotenv import load_dotenv load_dotenv() logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @click.command() @click.option('--host', default='localhost') @click.option('--port', default=10002) def main(host: str, port: int) -> None: """Start the reimbursement agent server.""" # Check for API key only if Vertex AI is not configured. if os.getenv('GOOGLE_GENAI_USE_VERTEXAI') != 'TRUE' and not os.getenv( 'GEMINI_API_KEY' ): logger.error( 'GEMINI_API_KEY environment variable not set and ' 'GOOGLE_GENAI_USE_VERTEXAI is not TRUE.' ) sys.exit(1) try: capabilities = AgentCapabilities(streaming=True) skill = AgentSkill( id='process_reimbursement', name='Process Reimbursement Tool', description='Helps with the reimbursement process for users given the amount and purpose of the reimbursement.', tags=['reimbursement'], examples=[ 'Can you reimburse me $20 for my lunch with the clients?' ], ) agent_card = AgentCard( name='Reimbursement Agent', description='This agent handles the reimbursement process for the employees given the amount and purpose of the reimbursement.', url=f'http://{host}:{port}/', version='1.0.0', default_input_modes=ReimbursementAgent.SUPPORTED_CONTENT_TYPES, default_output_modes=ReimbursementAgent.SUPPORTED_CONTENT_TYPES, capabilities=capabilities, skills=[skill], ) request_handler = DefaultRequestHandler( agent_executor=ReimbursementAgentExecutor(), task_store=InMemoryTaskStore(), ) server = A2AStarletteApplication( agent_card=agent_card, http_handler=request_handler ) uvicorn.run(server.build(), host=host, port=port) except Exception: logger.exception('An error occurred during server startup') sys.exit(1) if __name__ == '__main__': main() ``` -------------------------------- ### Get Task with History Example Source: https://a2a-protocol.org/latest/specification Shows how to retrieve a specific task by its ID and request its history length using a query parameter. The parameter `historyLength` is used to specify the amount of history to retrieve. ```http GET /tasks/{id}?historyLength=10 ``` -------------------------------- ### HTTP GET Request with A2A-Version Parameter Source: https://a2a-protocol.org/latest/specification Clients may provide the A2A-Version as a request parameter instead of a header. This example demonstrates a GET request using the version parameter. ```HTTP GET /tasks/task-123?A2A-Version=1.0 HTTP/1.1 Host: agent.example.com Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Accept: application/json ``` -------------------------------- ### Helloworld Server Startup Output Source: https://a2a-protocol.org/latest/tutorials/python/5-start-server This is the expected output when the Uvicorn server for the Helloworld agent starts successfully. It indicates the server is running and listening on a specific address. ```text INFO: Started server process [xxxxx] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:9999 (Press CTRL+C to quit) ``` -------------------------------- ### Agent Declaring Extension Support Source: https://a2a-protocol.org/latest/specification An AgentCard example showing how an agent declares its supported extensions, including URIs, descriptions, and whether they are required. ```json { "name": "Research Assistant Agent", "description": "AI agent for academic research and fact-checking", "supportedInterfaces": [ { "url": "https://research-agent.example.com/a2a/v1", "protocolBinding": "HTTP+JSON", "protocolVersion": "0.3" } ], "capabilities": { "streaming": false, "pushNotifications": false, "extensions": [ { "uri": "https://standards.org/extensions/citations/v1", "description": "Provides citation formatting and source verification", "required": false }, { "uri": "https://example.com/extensions/geolocation/v1", "description": "Location-based search capabilities", "required": false } ] }, "defaultInputModes": ["text/plain"], "defaultOutputModes": ["text/plain"], "skills": [ { "id": "academic-research", "name": "Academic Research Assistant", "description": "Provides research assistance with citations and source verification", "tags": ["research", "citations", "academic"], "examples": ["Find peer-reviewed articles on climate change"], "inputModes": ["text/plain"], "outputModes": ["text/plain"] } ] } ``` -------------------------------- ### Run LangGraph Agent Server Source: https://a2a-protocol.org/latest/tutorials/python/7-streaming-and-multiturn Navigate to the app directory and execute this command to start the LangGraph agent server. The server typically runs on http://localhost:10000. ```bash python __main__.py ``` -------------------------------- ### Legacy FilePart Representation Source: https://a2a-protocol.org/latest/specification This example shows the legacy format for FilePart, which also used the 'kind' field for type discrimination. ```json { "kind": "file", "file": { "name": "diagram.png", "mimeType": "image/png", "fileWithBytes": "iVBORw0KGgo..." } } ``` -------------------------------- ### Example Send Message Response Source: https://a2a-protocol.org/latest/specification Shows a successful HTTP response for a message send operation, containing a Task object with its current state. ```http HTTP/1.1 200 OK Content-Type: application/a2a+json { "task": { "id": "task-uuid", "contextId": "context-uuid", "status": { "state": "TASK_STATE_COMPLETED" } } } ``` -------------------------------- ### Example Request with A2A Service Parameters Source: https://a2a-protocol.org/latest/specification Demonstrates how to include A2A service parameters in an HTTP POST request. Service parameter names are transmitted as HTTP header fields. ```http POST /message:send HTTP/1.1 Host: agent.example.com Content-Type: application/a2a+json Authorization: Bearer token A2A-Version: 0.3 A2A-Extensions: https://example.com/extensions/geolocation/v1,https://standards.org/extensions/citations/v1 { "message": { "role": "ROLE_USER", "parts": [{"text": "Find restaurants near me"}] } } ``` -------------------------------- ### Example Send Message Request Source: https://a2a-protocol.org/latest/specification Illustrates the JSON payload for sending a message using the HTTP+JSON protocol. Includes message content and configuration options. ```http POST /message:send Content-Type: application/a2a+json { "message": { "messageId": "uuid", "role": "ROLE_USER", "parts": [{"text": "Hello"}] }, "configuration": { "acceptedOutputModes": ["text/plain"] } } ``` -------------------------------- ### Streaming Request Example Source: https://a2a-protocol.org/latest/specification Defines the request for initiating a streaming connection. It specifies the HTTP method, endpoint, and content type, along with the expected request body object. ```http POST /message:stream Content-Type: application/a2a+json { /* SendMessageRequest object */ } ``` -------------------------------- ### HTTP Client Opting into Extensions Source: https://a2a-protocol.org/latest/specification An example of an HTTP client opting into specific extensions using the 'A2A-Extensions' header and providing extension-specific metadata in the request body. ```http POST /message:send HTTP/1.1 Host: agent.example.com Content-Type: application/a2a+json Authorization: Bearer token A2A-Extensions: https://example.com/extensions/geolocation/v1,https://standards.org/extensions/citations/v1 { "message": { "role": "ROLE_USER", "parts": [{"text": "Find restaurants near me"}], "extensions": ["https://example.com/extensions/geolocation/v1"], "metadata": { "https://example.com/extensions/geolocation/v1": { "latitude": 37.7749, "longitude": -122.4194 } } } } ``` -------------------------------- ### Non-Streaming Response Example Source: https://a2a-protocol.org/latest/tutorials/python/6-interact-with-server This snippet shows a non-streaming response from an agent, including task details, artifacts, and history. It's useful for understanding single-response interactions. ```protobuf // Non-streaming response task { id: "xxxxxxxx" context_id: "yyyyyyyy" status { state: TASK_STATE_COMPLETED } artifacts { artifact_id: "zzzzzzzz" name: "result" parts { text: "Hello, World!" } } history { message_id: "vvvvvvvv" context_id: "yyyyyyyy" task_id: "xxxxxxxx" role: ROLE_USER parts { text: "Say hello." } } history { message_id: "wwwwwwww" role: ROLE_AGENT parts { text: "Processing request..." } } } ``` -------------------------------- ### Python Server Initialization and Startup Source: https://a2a-protocol.org/latest/tutorials/python/5-start-server This snippet demonstrates the complete setup for a Python server, including defining agent skills, public and extended agent cards, request handlers, routes, and finally running the server with Uvicorn. It covers the core logic for initializing an A2A server. ```Python import uvicorn from a2a.server.request_handlers import DefaultRequestHandler from a2a.server.routes import ( create_agent_card_routes, create_jsonrpc_routes, ) from a2a.server.tasks import InMemoryTaskStore from a2a.types import ( AgentCapabilities, AgentCard, AgentInterface, AgentSkill, ) from agent_executor import ( HelloWorldAgentExecutor, # type: ignore[import-untyped] ) from starlette.applications import Starlette if __name__ == '__main__': # Defines the abilities or functions that agent can perform. skill = AgentSkill( id='echo_bot', name='Echo Bot', description='An example agent that acknowledges client request and responds with a "Hello World" message.', input_modes=['text/plain'], output_modes=['text/plain'], tags=['a2a', 'echo-example'], examples=['hi', 'how are you'], ) # Defines an optional additional skill for the agent that is not visible in the public card. extended_skill = AgentSkill( id='echo_bot_super_mode', name='Echo Bot (Super Mode)', description='An extended version of Echo Bot that responds with extra enthusiasm!', tags=['a2a', 'echo-example', 'extended'], examples=['super hi', 'give me a super hello'], ) # Define a public-facing agent card that allows clients to discover your agent's capabilities. public_agent_card = AgentCard( # Basic identity information of A2A server name='Hello World Agent', # Identity description='Just a hello world agent', version='0.0.1', # Default Media Types for the agent's interactions default_input_modes=['text/plain'], # Supported media types default_output_modes=['text/plain'], # Supported A2A features (like streaming or extended config) capabilities=AgentCapabilities(streaming=True, extended_agent_card=True), # Ordered list of endpoints and protocols where the service can be reached supported_interfaces=[ AgentInterface( protocol_binding='JSONRPC', url='http://127.0.0.1:9999', ) ], # The list of AgentSkill objects that this agent offers skills=[skill], # Optional attributes (omitted here for simplicity): # icon_url -> A URL to an icon representing the agent ) # Defines the authenticated extended agent card with # extended skills that are visible only to authenticated users extended_agent_card = AgentCard( name='Hello World Agent - Extended Edition', description='The full-featured hello world agent for authenticated users.', version='0.0.2', default_input_modes=['text/plain'], default_output_modes=['text/plain'], capabilities=AgentCapabilities(streaming=True, extended_agent_card=True), supported_interfaces=[ AgentInterface( protocol_binding='JSONRPC', url='http://127.0.0.1:9999', ) ], skills=[ skill, extended_skill, ], # Both skills for the extended card ) # The RequestHandler processes incoming requests and manages tasks request_handler = DefaultRequestHandler( # Agent executor handles the execution of the client requests agent_executor=HelloWorldAgentExecutor(), # The task_store is used to store and manage tasks task_store=InMemoryTaskStore(), # Public agent card for unauthenticated users agent_card=public_agent_card, # Extended agent card for authenticated users extended_agent_card=extended_agent_card, ) # Creating the routes for the A2A server # These routes handle the incoming requests from the clients # and the outgoing responses to the clients routes = [] # Create routes for the agent card routes.extend(create_agent_card_routes(public_agent_card)) # Create routes for the JSONRPC protocol # Alternatively, you can choose GRPC or HTTP_JSON as protocol bindings # based on your requirements routes.extend(create_jsonrpc_routes(request_handler, '/')) # Create a web app with the defined routes # Here we are using Starlette, a lightweight ASGI web framework to serve the agent # Alternatively, you can choose FastAPI or other ASGI frameworks app = Starlette(routes=routes) # Run the app # Uvicorn is a production-ready ASGI HTTP server uvicorn.run(app, host='127.0.0.1', port=9999) ``` -------------------------------- ### DatabasePushNotificationConfigStore.initialize Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.server.tasks.database_push_notification_config_store.html Initialize the database and create the table if needed. ```APIDOC ## initialize ### Description Initialize the database and create the table if needed. ### Method async ### Response #### Success Response (200) - None ``` -------------------------------- ### HTTP GET Request with A2A-Version Header Source: https://a2a-protocol.org/latest/specification Clients must send the A2A-Version header with each request to maintain compatibility. This example shows a GET request including the version header. ```HTTP GET /tasks/task-123 HTTP/1.1 Host: agent.example.com A2A-Version: 1.0 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Accept: application/json ``` -------------------------------- ### Run the Helloworld Test Client Source: https://a2a-protocol.org/latest/tutorials/python/6-interact-with-server Execute the Python test client script from the a2a-samples directory to interact with the server. ```bash # from the a2a-samples directory python samples/python/agents/helloworld/test_client.py ``` -------------------------------- ### GET Request for Authenticated Extended Agent Card Source: https://a2a-protocol.org/latest/specification Client sends a GET request to /extendedAgentCard with an Authorization header to retrieve detailed information after authenticating. ```http GET /extendedAgentCard HTTP/1.1 Host: agent.example.com Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` -------------------------------- ### Create .env File for Gemini API Key Source: https://a2a-protocol.org/latest/tutorials/python/7-streaming-and-multiturn Create a .env file in the specified directory and add your Gemini API key. This is required for the agent to authenticate with the Gemini model. ```bash echo "GOOGLE_API_KEY=YOUR_API_KEY_HERE" > .env ``` -------------------------------- ### AgentCardSignature JSON Example Source: https://a2a-protocol.org/latest/specification An example of the AgentCardSignature object, which includes the base64url-encoded protected header and the signature value. This format is used to represent JWS components. ```json { "protected": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpPU0UiLCJraWQiOiJrZXktMSIsImprdSI6Imh0dHBzOi8vZXhhbXBsZS5jb20vYWdlbnQvandrcy5qc29uIn0", "signature": "QFdkNLNszlGj3z3u0YQGt_T9LixY3qtdQpZmsTdDHDe3fXV9y9-B3m2-XgCpzuhiLt8E0tV6HXoZKHv4GtHgKQ" } ``` -------------------------------- ### Initialize Request Handler and Server Source: https://a2a-protocol.org/latest/tutorials/python/7-streaming-and-multiturn Sets up the asynchronous HTTP client, push notification configuration, and the main A2A server application with a default request handler. This is typically done in the main server setup file. ```python httpx_client = httpx.AsyncClient() push_config_store = InMemoryPushNotificationConfigStore() push_sender = BasePushNotificationSender(httpx_client=httpx_client, config_store=push_config_store) request_handler = DefaultRequestHandler( agent_executor=CurrencyAgentExecutor(), task_store=InMemoryTaskStore(), push_config_store=push_config_store, push_sender= push_sender ) server = A2AStarletteApplication( agent_card=agent_card, http_handler=request_handler ) uvicorn.run(server.build(), host=host, port=port) ``` -------------------------------- ### SendStreamingMessage SSE Response Example Source: https://a2a-protocol.org/latest/specification Example of Server-Sent Events (SSE) responses for the SendStreamingMessage method. Each data chunk contains a JSON-RPC 2.0 result for a stream update. ```sse data: {"jsonrpc": "2.0", "id": 1, "result": { /* StreamResponse object */ }} data: {"jsonrpc": "2.0", "id": 1, "result": { /* StreamResponse object */ }} ``` -------------------------------- ### Go Example: gRPC Request with A2A Service Parameters Source: https://a2a-protocol.org/latest/specification Shows how to set A2A service parameters like authorization, version, and extensions as metadata in a gRPC request using Go. ```go // Go example using gRPC metadata md := metadata.Pairs( "authorization", "Bearer token", "a2a-version", "0.3", "a2a-extensions", "https://example.com/extensions/geolocation/v1,https://standards.org/extensions/citations/v1", ) ctx := metadata.NewOutgoingContext(context.Background(), md) // Make the RPC call with the context containing metadata response, err := client.SendMessage(ctx, request) ``` -------------------------------- ### GET /api/tasks Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.transports.grpc.html Retrieves tasks for an agent. ```APIDOC ## GET /api/tasks ### Description Retrieves tasks for an agent. ### Method GET ### Endpoint /api/tasks ### Request Body - **request** (ListTasksRequest) - Required - The request object to list tasks. ``` -------------------------------- ### POST /api/subscribe_to_task Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.transports.grpc.html Reconnects to get task updates. ```APIDOC ## POST /api/subscribe_to_task ### Description Reconnects to get task updates. ### Method POST ### Endpoint /api/subscribe_to_task ### Request Body - **request** (SubscribeToTaskRequest) - Required - The request object to subscribe to task updates. ``` -------------------------------- ### List Tasks with Filtering Example Source: https://a2a-protocol.org/latest/specification Demonstrates how to list tasks with various query parameters including context ID, status, page size, and page token. Parameters are camelCased versions of Protocol Buffer field names. ```http GET /tasks?contextId=uuid&status=TASK_STATE_WORKING&pageSize=50&pageToken=cursor ``` -------------------------------- ### GetTask Source: https://a2a-protocol.org/latest/definitions Gets the latest state of a specific task by its ID. ```APIDOC ## GET /tasks/{id= *} ### Description Gets the latest state of a task. ### Method GET ### Endpoint /tasks/{id= *} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the task. ### Response #### Success Response (200) - **** (Task) - The task object. ## GET /{tenant}/tasks/{id= *} ### Description Gets the latest state of a task within a specific tenant. ### Method GET ### Endpoint /{tenant}/tasks/{id= *} ### Parameters #### Path Parameters - **tenant** (string) - Required - The tenant identifier. - **id** (string) - Required - The ID of the task. ### Response #### Success Response (200) - **** (Task) - The task object. ``` -------------------------------- ### Initialize Streaming Client and Send Message Source: https://a2a-protocol.org/latest/tutorials/python/6-interact-with-server Creates a streaming client and sends a message. The response is streamed chunk by chunk. Remember to close the client after use. ```python print('\nInitializing a streaming client.') client_config = ClientConfig(streaming=True) # Streaming client = await create_client(agent=public_agent_card, client_config=client_config) print('Response:') async for chunk in client.send_message(request): print(chunk) # Call await streaming_client.close() after the loop to release the underlying HTTP connection. ``` -------------------------------- ### GET /tasks Source: https://a2a-protocol.org/latest/specification Retrieves a list of tasks with optional pagination parameters. ```APIDOC ## GET /tasks ### Description Retrieves a list of tasks, supporting pagination via `pageToken` and controlling the number of results with `pageSize`. A `contextId` can be used to filter tasks. ### Method GET ### Endpoint /tasks ### Parameters #### Query Parameters - **contextId** (string) - Optional - The context ID to filter tasks. - **pageSize** (integer) - Optional - The number of tasks to return per page. Must be between 1 and 100. - **pageToken** (string) - Optional - A base64-encoded cursor token for retrieving the next page of results. ### Response #### Success Response (200) - **tasks** (array) - A list of task objects. - **totalSize** (integer) - The total number of tasks available. - **pageSize** (integer) - The number of tasks returned in this response. - **nextPageToken** (string) - A base64-encoded cursor token for the next page of results, if available. #### Response Example ```json { "tasks": [], "totalSize": 15, "pageSize": 10, "nextPageToken": "base64-encoded-next-cursor-token" } ``` ### Error Handling - **400 Bad Request**: Returned for invalid parameters such as `pageSize` out of range, negative `historyLength`, or invalid `status` values. ``` -------------------------------- ### GET /api/tasks/push_notification_configs Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.transports.grpc.html Lists push notification configurations for a specific task. ```APIDOC ## GET /api/tasks/push_notification_configs ### Description Lists push notification configurations for a specific task. ### Method GET ### Endpoint /api/tasks/push_notification_configs ### Request Body - **request** (ListTaskPushNotificationConfigsRequest) - Required - The request object to list configurations. ``` -------------------------------- ### Create Client from URL Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.client_factory.html Resolve an AgentCard from a URL and create a client. This is useful when the AgentCard is not readily available. ```python client = await factory.create_from_url(’https://example.com’) ``` -------------------------------- ### GET /api/agents/{agentId}/card Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.transports.grpc.html Retrieves the agent’s card. ```APIDOC ## GET /api/agents/{agentId}/card ### Description Retrieves the agent’s card. ### Method GET ### Endpoint /api/agents/{agentId}/card ### Parameters #### Path Parameters - **agentId** (string) - Required - The ID of the agent whose card to retrieve. #### Request Body - **request** (GetExtendedAgentCardRequest) - Required - The request object to get the agent card. ``` -------------------------------- ### HelloWorldAgentExecutor Initialization Source: https://a2a-protocol.org/latest/tutorials/python/4-agent-executor Initializes the HelloWorldAgentExecutor by instantiating the HelloWorldAgent. ```python class HelloWorldAgentExecutor(AgentExecutor): """Test AgentProxy Implementation.""" def __init__(self) -> None: self.agent = HelloWorldAgent() ``` -------------------------------- ### GET /api/tasks/{taskId} Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.transports.grpc.html Retrieves the current state and history of a specific task. ```APIDOC ## GET /api/tasks/{taskId} ### Description Retrieves the current state and history of a specific task. ### Method GET ### Endpoint /api/tasks/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The ID of the task to retrieve. #### Request Body - **request** (GetTaskRequest) - Required - The request object to get the task details. ``` -------------------------------- ### Client Sends Initial Message Source: https://a2a-protocol.org/latest/topics/life-of-a-task The client initiates a task by sending a message to the agent. This message includes the task details and the user's request. ```json { "jsonrpc": "2.0", "id": "req-001", "method": "SendMessage", "params": { "message": { "role": "user", "parts": [ { "text": "Generate an image of a sailboat on the ocean." } ], "messageId": "msg-user-001" } } } ``` -------------------------------- ### Get Push Notification Configuration Source: https://a2a-protocol.org/latest/specification Retrieves a specific push notification configuration for a task. ```APIDOC ## GET /tasks/{id}/pushNotificationConfigs/{configId} ### Description Retrieves a specific push notification configuration for a given task. ### Method GET ### Endpoint /tasks/{id}/pushNotificationConfigs/{configId} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the task. - **configId** (string) - Required - The unique identifier of the push notification configuration. ``` -------------------------------- ### Subscribe to Task Source: https://a2a-protocol.org/latest/specification Establishes a streaming connection to receive updates for an existing task. ```APIDOC ## Subscribe to Task ### Description Establishes a streaming connection to receive updates for an existing task. This allows for real-time monitoring of task progress. ### Method POST (Assumed based on operation type) ### Endpoint /tasks/{id}/subscribe (Assumed path structure) ### Parameters #### Path Parameters - **id** (string) - Yes - The resource ID of the task to subscribe to. #### Query Parameters - **tenant** (string) - No - Optional. Opaque routing identifier. Must match the `tenant` value from the selected `AgentInterface` in the Agent Card when that field is set. ### Response #### Success Response (200) - **Stream Response** (object) - Contains an initial `Task` object and a stream of `TaskStatusUpdateEvent` and `TaskArtifactUpdateEvent` objects. #### Errors - **UnsupportedOperationError**: Streaming is not supported by the agent or the operation is attempted on a task in a terminal state. - **TaskNotFoundError**: The task ID does not exist or is not accessible. ``` -------------------------------- ### Get Task Status Source: https://a2a-protocol.org/latest/specification Retrieves the current status of a specific task using its ID. ```APIDOC ## GET /tasks/{id} ### Description Retrieves the status of a specific task. ### Method GET ### Endpoint /tasks/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the task. ``` -------------------------------- ### GET /api/tasks/{taskId}/push_notification_config Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.transports.grpc.html Retrieves the push notification configuration for a specific task. ```APIDOC ## GET /api/tasks/{taskId}/push_notification_config ### Description Retrieves the push notification configuration for a specific task. ### Method GET ### Endpoint /api/tasks/{taskId}/push_notification_config ### Parameters #### Path Parameters - **taskId** (string) - Required - The ID of the task. #### Request Body - **request** (GetTaskPushNotificationConfigRequest) - Required - The request object to get the configuration. ``` -------------------------------- ### Create ClientFactory Instance Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.client_factory.html Instantiate ClientFactory with optional configuration. Custom transport producers can be registered using the register method. ```python factory = ClientFactory(config) factory.register(‘my_custom_transport’, custom_transport_producer) ``` -------------------------------- ### Legacy TaskArtifactUpdateEvent Representation Source: https://a2a-protocol.org/latest/specification Example of the legacy TaskArtifactUpdateEvent format, employing the 'kind' field. ```json { "kind": "artifact-update", "taskId": "...", "artifact": {...} } ``` -------------------------------- ### Clone A2A Samples Repository Source: https://a2a-protocol.org/latest/tutorials/python/2-setup Clone the A2A Samples repository to your local machine. Use the 'main' branch and a depth of 1 for a shallow clone. Navigate into the cloned directory. ```bash git clone https://github.com/a2aproject/a2a-samples.git -b main --depth 1 cd a2a-samples ``` -------------------------------- ### Get Task Source: https://a2a-protocol.org/latest/specification Retrieves the current state, including status and artifacts, of a previously initiated task. ```APIDOC ## GET /tasks/{id} ### Description Retrieves the current state, including status and artifacts, of a previously initiated task. This is typically used for polling the status of a task or fetching its final state. ### Method GET ### Endpoint /tasks/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The resource ID of the task to retrieve. - **tenant** (string) - Optional - Opaque routing identifier. #### Query Parameters - **historyLength** (integer) - Optional - The maximum number of most recent messages from the task's history to retrieve. An unset value means the client does not impose any limit. A value of zero is a request to not include any messages. ### Response #### Success Response - **Task** (object) - Current state and artifacts of the requested task. #### Errors - **TaskNotFoundError**: The task ID does not exist or is not accessible. ``` -------------------------------- ### ClientFactory.create_from_url() Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.client.client_factory.html Creates a Client by resolving an AgentCard from a URL. ```APIDOC ## Method: ClientFactory.create_from_url() ### Description Create a Client by resolving an AgentCard from a URL. Resolves the agent card from the given URL using the factory’s configured httpx client, then creates a client via create. If the agent card is already available, use create directly instead. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **url** (str) - The base URL of the agent. The agent card will be fetched from /.well-known/agent-card.json by default. - **interceptors** (list[ClientCallInterceptor] | None) - A list of interceptors to use for each request. These are used for things like attaching credentials or http headers to all outbound requests. - **relative_card_path** (str | None) - The relative path when resolving the agent card. See A2ACardResolver.get_agent_card for details. - **resolver_http_kwargs** (dict[str, Any] | None) - Dictionary of arguments to provide to the httpx client when resolving the agent card. - **signature_verifier** (Callable[[AgentCard], None] | None) - A callable used to verify the agent card’s signatures. ### Returns - **Client** - A Client object. ``` -------------------------------- ### Get Task Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.server.request_handlers.html Retrieves the state and history of a specific task. Default handler for ‘tasks/get’. ```APIDOC ## GET /websites/a2a-protocol/tasks/get ### Description Retrieves the state and history of a specific task. ### Method GET ### Endpoint /websites/a2a-protocol/tasks/get ### Parameters #### Query Parameters - **params** (object) - Required - Parameters specifying the task ID and optionally history length. - **context** (object) - Required - Context provided by the server. ### Response #### Success Response (200) - **Task | None** (object) - The Task object if found, otherwise None. ``` -------------------------------- ### HelloWorldAgentExecutor Execute Method Source: https://a2a-protocol.org/latest/tutorials/python/4-agent-executor Processes user requests, manages task creation and updates, invokes the agent, and adds results as artifacts. Use this to handle incoming requests and generate responses. ```python async def execute( self, context: RequestContext, event_queue: EventQueue, ) -> None: """Process user request.""" # 1. Collect a task from request context if context.current_task: task = context.current_task else: # 1.1 If there is no task, create one and add it event queue task = new_task_from_user_message(context.message) await event_queue.enqueue_event(task) # 2. Update task status in EventQueue using TaskUpdater class object task_updater = TaskUpdater( event_queue=event_queue, task_id=task.id, context_id=task.context_id ) await task_updater.update_status( state=TaskState.TASK_STATE_WORKING, message=new_text_message('Processing request...'), ) # 3. Collect user request from request content and invoke LLM agent to generate content query = get_message_text(context.message) if query: result = await self.agent.invoke(user_request=query) else: result = 'No text input is provided!' # 4. Add generated response as an artifact to EventQueue await task_updater.add_artifact(parts=[new_text_part(text=result, media_type='text/plain')]) print('Result: ', result) # 5. Update task status to completed await task_updater.update_status( state=TaskState.TASK_STATE_COMPLETED, message=new_text_message('Request is completed!'), ) ``` -------------------------------- ### Get Extended Agent Card Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.server.request_handlers.html Retrieves the extended agent card for the agent. Requires capabilities.extended_agent_card to be true. ```APIDOC ## GET /websites/a2a-protocol/extended_agent_card ### Description Retrieves the extended agent card for the agent. ### Method GET ### Endpoint /websites/a2a-protocol/extended_agent_card ### Parameters #### Query Parameters - **params** (object) - Required - Parameters for the request. - **context** (object) - Required - Context provided by the server. ### Response #### Success Response (200) - **AgentCard** (object) - The AgentCard object representing the extended properties of the agent. ``` -------------------------------- ### Legacy DataPart Representation Source: https://a2a-protocol.org/latest/specification Example of the legacy DataPart format, utilizing the 'kind' field for type identification. ```json { "kind": "data", "data": {...} } ``` -------------------------------- ### Create and Activate Python Virtual Environment (venv) Source: https://a2a-protocol.org/latest/tutorials/python/2-setup Create a virtual environment using Python's built-in 'venv' module. Activate the environment to isolate project dependencies. This is recommended for managing Python projects. ```bash python -m venv .venv source .venv/bin/activate ``` ```bash python -m venv .venv .venv\Scripts\activate ``` -------------------------------- ### Get task Source: https://a2a-protocol.org/latest/specification Retrieves a specific task by its ID. This operation is available via JSON-RPC, gRPC, and REST bindings. ```APIDOC ## GET /tasks/{id} ### Description Retrieves a task by its ID. ### Method GET ### Endpoint /tasks/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the task. ### Response #### Success Response (200) This endpoint returns the details of the requested task. Specific fields are not detailed in the source. ``` -------------------------------- ### a2a.a2a_db_cli.run_migrations() Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.a2a_db_cli.html A command-line interface tool designed to manage and execute database migrations. ```APIDOC ## a2a.a2a_db_cli.run_migrations() ### Description CLI tool to manage database migrations. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters None ### Request Example ```python from a2a.a2a_db_cli import run_migrations # This function is typically called from the command line # Example CLI usage: python -m a2a.a2a_db_cli run_migrations run_migrations() ``` ### Response #### Success Response (None) - This function does not return a value; it performs actions related to database migrations. ``` -------------------------------- ### QueueManager Source: https://a2a-protocol.org/latest/sdk/python/api/a2a.server.events.html Abstract base class for queue managers. Defines methods for adding, closing, creating/tapping, and getting queues. ```APIDOC ## Class QueueManager ### Description An abstract base class defining the interface for queue management operations. Concrete implementations will manage specific types of queues. ### Methods #### `add(queue_name, queue)` - **Description**: Adds a queue to the manager. - **Parameters**: - `queue_name` (string): The name of the queue. - `queue`: The queue object to add. #### `close()` - **Description**: Closes all managed queues. #### `create_or_tap(queue_name)` - **Description**: Creates a queue if it does not exist, or returns an existing one. Also supports tapping into a queue. - **Parameters**: - `queue_name` (string): The name of the queue. - **Returns**: The queue object. #### `get(queue_name)` - **Description**: Retrieves a queue by its name. - **Parameters**: - `queue_name` (string): The name of the queue. - **Returns**: The requested queue object. #### `tap(queue_name)` - **Description**: Returns a queue that can be tapped for observing events. - **Parameters**: - `queue_name` (string): The name of the queue to tap. ``` -------------------------------- ### Activate Python Virtual Environment (Mac/Linux) Source: https://a2a-protocol.org/latest/tutorials/python/6-interact-with-server Activate the virtual environment on macOS or Linux systems before running the client script. ```bash source .venv/bin/activate ``` -------------------------------- ### Activate Python Virtual Environment (Windows) Source: https://a2a-protocol.org/latest/tutorials/python/6-interact-with-server Activate the virtual environment on Windows systems before running the client script. ```bash .venv\Scripts\activate ``` -------------------------------- ### A2A-Version HTTP Header Example Source: https://a2a-protocol.org/latest/specification Indicates the A2A protocol version the client is using. The value must be in the format Major.Minor. ```http A2A-Version: 0.3 ``` -------------------------------- ### Original Agent Card Fragment Source: https://a2a-protocol.org/latest/specification An example of an Agent Card fragment before canonicalization, showing various fields and their initial values. ```json { "name": "Example Agent", "description": "", "capabilities": { "streaming": false, "pushNotifications": false, "extensions": [] }, "skills": [] } ``` -------------------------------- ### Run LangGraph Agent Test Client Source: https://a2a-protocol.org/latest/tutorials/python/7-streaming-and-multiturn Open a new terminal, navigate to the app directory, and run this command to interact with the LangGraph agent using its test client. ```bash python test_client.py ```