|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import asyncio |
| 3 | +import httpx |
| 4 | +import json |
| 5 | +import uuid |
| 6 | +import argparse |
| 7 | +import sys |
| 8 | + |
| 9 | + |
| 10 | +async def validate_agent_card(client, agent_url): |
| 11 | + """ |
| 12 | + Validates the agent by fetching its well-known agent card. |
| 13 | + """ |
| 14 | + card_url = f"{agent_url.rstrip('/')}/.well-known/agent-card.json" |
| 15 | + print(f"Fetching agent card from: {card_url}") |
| 16 | + try: |
| 17 | + resp = await client.get(card_url) |
| 18 | + if resp.status_code == 200: |
| 19 | + try: |
| 20 | + card_data = resp.json() |
| 21 | + print(f"Agent Card Found: {json.dumps(card_data, indent=2)}") |
| 22 | + return True |
| 23 | + except json.JSONDecodeError: |
| 24 | + print(f"Failed to decode agent card JSON from {card_url}") |
| 25 | + return False |
| 26 | + else: |
| 27 | + print(f"Failed to fetch agent card. Status Code: {resp.status_code}") |
| 28 | + return False |
| 29 | + except httpx.RequestError as e: |
| 30 | + print(f"Connection failed to {card_url}: {e}") |
| 31 | + return False |
| 32 | + |
| 33 | + |
| 34 | +async def send_message(client, agent_url, message_text): |
| 35 | + """ |
| 36 | + Sends a message to the agent via JSON-RPC. |
| 37 | + """ |
| 38 | + print(f"\nSending Message: '{message_text}' to {agent_url}") |
| 39 | + |
| 40 | + payload = { |
| 41 | + "jsonrpc": "2.0", |
| 42 | + "method": "message/send", |
| 43 | + "params": { |
| 44 | + "message": { |
| 45 | + "kind": "message", |
| 46 | + "role": "user", |
| 47 | + "parts": [{"kind": "text", "text": message_text}], |
| 48 | + "messageId": str(uuid.uuid4()), |
| 49 | + } |
| 50 | + }, |
| 51 | + "id": 1, |
| 52 | + } |
| 53 | + |
| 54 | + try: |
| 55 | + resp = await client.post( |
| 56 | + agent_url, json=payload, headers={"Content-Type": "application/json"} |
| 57 | + ) |
| 58 | + |
| 59 | + if resp.status_code != 200: |
| 60 | + print(f"Error sending message. Status Code: {resp.status_code}") |
| 61 | + print(resp.text) |
| 62 | + return None |
| 63 | + |
| 64 | + data = resp.json() |
| 65 | + if "error" in data: |
| 66 | + print(f"JSON-RPC Error: {data['error']}") |
| 67 | + return None |
| 68 | + |
| 69 | + if "result" in data and "id" in data["result"]: |
| 70 | + task_id = data["result"]["id"] |
| 71 | + print(f"Task Submitted with ID: {task_id}") |
| 72 | + return task_id |
| 73 | + else: |
| 74 | + print(f"Unexpected response format: {data}") |
| 75 | + return None |
| 76 | + |
| 77 | + except httpx.RequestError as e: |
| 78 | + print(f"Connection failed during message send: {e}") |
| 79 | + return None |
| 80 | + except json.JSONDecodeError: |
| 81 | + print(f"Failed to decode response JSON: {resp.text}") |
| 82 | + return None |
| 83 | + |
| 84 | + |
| 85 | +async def poll_task(client, agent_url, task_id): |
| 86 | + """ |
| 87 | + Polls the task status until completion. |
| 88 | + """ |
| 89 | + print(f"Polling for result for Task ID: {task_id}...") |
| 90 | + |
| 91 | + while True: |
| 92 | + await asyncio.sleep(2) |
| 93 | + poll_payload = { |
| 94 | + "jsonrpc": "2.0", |
| 95 | + "method": "tasks/get", |
| 96 | + "params": {"id": task_id}, |
| 97 | + "id": 2, |
| 98 | + } |
| 99 | + |
| 100 | + try: |
| 101 | + poll_resp = await client.post( |
| 102 | + agent_url, |
| 103 | + json=poll_payload, |
| 104 | + headers={"Content-Type": "application/json"}, |
| 105 | + ) |
| 106 | + |
| 107 | + if poll_resp.status_code != 200: |
| 108 | + print(f"Polling Failed: {poll_resp.status_code}") |
| 109 | + print(f"Details: {poll_resp.text}") |
| 110 | + break |
| 111 | + |
| 112 | + poll_data = poll_resp.json() |
| 113 | + |
| 114 | + if "error" in poll_data: |
| 115 | + print(f"Polling Error: {poll_data['error']}") |
| 116 | + break |
| 117 | + |
| 118 | + if "result" in poll_data: |
| 119 | + status = poll_data["result"].get("status", {}) |
| 120 | + state = status.get("state") |
| 121 | + print(f"Task State: {state}") |
| 122 | + |
| 123 | + if state not in ["submitted", "running", "working"]: |
| 124 | + print(f"\nTask Finished with state: {state}") |
| 125 | + return poll_data["result"] |
| 126 | + else: |
| 127 | + print(f"Unexpected polling response: {poll_data}") |
| 128 | + break |
| 129 | + |
| 130 | + except httpx.RequestError as e: |
| 131 | + print(f"Connection failed during polling: {e}") |
| 132 | + break |
| 133 | + except json.JSONDecodeError: |
| 134 | + print(f"Failed to decode polling response: {poll_resp.text}") |
| 135 | + break |
| 136 | + |
| 137 | + |
| 138 | +def print_result(result): |
| 139 | + """ |
| 140 | + Prints the final result from the agent. |
| 141 | + """ |
| 142 | + if not result: |
| 143 | + return |
| 144 | + |
| 145 | + history = result.get("history", []) |
| 146 | + if history: |
| 147 | + last_msg = None |
| 148 | + # Find the last message that is NOT from the user (i.e., the agent's response) |
| 149 | + for msg in reversed(history): |
| 150 | + if msg.get("role") != "user": |
| 151 | + last_msg = msg |
| 152 | + break |
| 153 | + |
| 154 | + if last_msg: |
| 155 | + print("\n--- Agent Response ---") |
| 156 | + if "parts" in last_msg: |
| 157 | + for part in last_msg["parts"]: |
| 158 | + if "text" in part: |
| 159 | + print(part["text"]) |
| 160 | + elif "content" in part: |
| 161 | + print(part["content"]) |
| 162 | + else: |
| 163 | + print(f"Final Message (No parts): {last_msg}") |
| 164 | + else: |
| 165 | + print("\n--- No Agent Response Found in History ---") |
| 166 | + |
| 167 | + # print(f"\nFull Result Debug:\n{json.dumps(result, indent=2)}") |
| 168 | + |
| 169 | + |
| 170 | +async def main(): |
| 171 | + parser = argparse.ArgumentParser( |
| 172 | + description="A2A Client for communicating with other agents." |
| 173 | + ) |
| 174 | + parser.add_argument( |
| 175 | + "--url", |
| 176 | + required=True, |
| 177 | + help="The base URL of the A2A Agent (e.g., http://agent.arpa/a2a/)", |
| 178 | + ) |
| 179 | + parser.add_argument( |
| 180 | + "--query", required=True, help="The message/query to send to the agent" |
| 181 | + ) |
| 182 | + |
| 183 | + args = parser.parse_args() |
| 184 | + |
| 185 | + agent_url = args.url |
| 186 | + query = args.query |
| 187 | + |
| 188 | + print("Initializing A2A Client...") |
| 189 | + print(f"Target Agent: {agent_url}") |
| 190 | + print(f"Query: {query}") |
| 191 | + |
| 192 | + async with httpx.AsyncClient(timeout=60.0) as client: |
| 193 | + # 1. Validate Agent |
| 194 | + if not await validate_agent_card(client, agent_url): |
| 195 | + print("Agent validation failed. Aborting.") |
| 196 | + sys.exit(1) |
| 197 | + |
| 198 | + # 2. Send Message |
| 199 | + task_id = await send_message(client, agent_url, query) |
| 200 | + if not task_id: |
| 201 | + print("Failed to submit task. Aborting.") |
| 202 | + sys.exit(1) |
| 203 | + |
| 204 | + # 3. Poll for Result |
| 205 | + result = await poll_task(client, agent_url, task_id) |
| 206 | + |
| 207 | + # 4. Print Result |
| 208 | + print_result(result) |
| 209 | + |
| 210 | + |
| 211 | +if __name__ == "__main__": |
| 212 | + asyncio.run(main()) |
0 commit comments