|
| 1 | + |
| 2 | +import asyncio |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import uuid |
| 6 | +from datetime import datetime, timezone |
| 7 | + |
| 8 | +from datetime import datetime, timezone |
| 9 | + |
| 10 | +from fastapi import FastAPI |
| 11 | +from uvicorn import Config, Server |
| 12 | + |
| 13 | + |
| 14 | +from a2a.server.agent_execution.agent_executor import AgentExecutor |
| 15 | +from a2a.server.agent_execution.context import RequestContext |
| 16 | +from a2a.server.events.event_queue import EventQueue |
| 17 | +from a2a.server.events.in_memory_queue_manager import InMemoryQueueManager |
| 18 | +from a2a.server.request_handlers.default_request_handler import DefaultRequestHandler |
| 19 | +from a2a.server.apps.jsonrpc.fastapi_app import A2AFastAPIApplication |
| 20 | +from a2a.server.apps.jsonrpc.fastapi_app import A2AFastAPIApplication |
| 21 | +from a2a.types import ( |
| 22 | + AgentCard, |
| 23 | + AgentCapabilities, |
| 24 | + AgentProvider, |
| 25 | + Message, |
| 26 | + TextPart, |
| 27 | + Task, |
| 28 | + TaskState, |
| 29 | + TaskStatus, |
| 30 | + TaskStatusUpdateEvent, |
| 31 | +) |
| 32 | +from a2a.auth.user import UnauthenticatedUser |
| 33 | +from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore |
| 34 | + |
| 35 | +# Configure logging |
| 36 | +logging.basicConfig(level=logging.INFO) |
| 37 | +logger = logging.getLogger("SUTAgent") |
| 38 | + |
| 39 | +class SUTAgentExecutor(AgentExecutor): |
| 40 | + def __init__(self): |
| 41 | + self.running_tasks = set() |
| 42 | + self.last_context_id = None |
| 43 | + |
| 44 | + async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None: |
| 45 | + api_task_id = context.task_id |
| 46 | + if api_task_id in self.running_tasks: |
| 47 | + self.running_tasks.remove(api_task_id) |
| 48 | + |
| 49 | + status_update = TaskStatusUpdateEvent( |
| 50 | + task_id=api_task_id, |
| 51 | + context_id=self.last_context_id or str(uuid.uuid4()), |
| 52 | + status=TaskStatus( |
| 53 | + state=TaskState.canceled, |
| 54 | + timestamp=datetime.now(timezone.utc).isoformat(), |
| 55 | + ), |
| 56 | + final=True, |
| 57 | + ) |
| 58 | + await event_queue.enqueue_event(status_update) |
| 59 | + |
| 60 | + async def execute(self, context: RequestContext, event_queue: EventQueue) -> None: |
| 61 | + user_message = context.message |
| 62 | + task_id = context.task_id |
| 63 | + context_id = context.context_id |
| 64 | + self.last_context_id = context_id |
| 65 | + |
| 66 | + self.running_tasks.add(task_id) |
| 67 | + |
| 68 | + logger.info( |
| 69 | + f"[SUTAgentExecutor] Processing message {user_message.message_id} " |
| 70 | + f"for task {task_id} (context: {context_id})" |
| 71 | + ) |
| 72 | + |
| 73 | + working_status = TaskStatusUpdateEvent( |
| 74 | + task_id=task_id, |
| 75 | + context_id=context_id, |
| 76 | + status=TaskStatus( |
| 77 | + state=TaskState.working, |
| 78 | + message=Message( |
| 79 | + role="agent", |
| 80 | + message_id=str(uuid.uuid4()), |
| 81 | + parts=[TextPart(text="Processing your question")], |
| 82 | + task_id=task_id, |
| 83 | + context_id=context_id, |
| 84 | + ), |
| 85 | + timestamp=datetime.now(timezone.utc).isoformat(), |
| 86 | + ), |
| 87 | + final=False, |
| 88 | + ) |
| 89 | + await event_queue.enqueue_event(working_status) |
| 90 | + |
| 91 | + agent_reply_text = "Hello world!" |
| 92 | + await asyncio.sleep(3) # Simulate processing delay |
| 93 | + |
| 94 | + if task_id not in self.running_tasks: |
| 95 | + logger.info(f"Task {task_id} was cancelled.") |
| 96 | + return |
| 97 | + |
| 98 | + logger.info(f"[SUTAgentExecutor] Response: {agent_reply_text}") |
| 99 | + |
| 100 | + agent_message = Message( |
| 101 | + role="agent", |
| 102 | + message_id=str(uuid.uuid4()), |
| 103 | + parts=[TextPart(text=agent_reply_text)], |
| 104 | + task_id=task_id, |
| 105 | + context_id=context_id, |
| 106 | + ) |
| 107 | + |
| 108 | + final_update = TaskStatusUpdateEvent( |
| 109 | + task_id=task_id, |
| 110 | + context_id=context_id, |
| 111 | + status=TaskStatus( |
| 112 | + state=TaskState.input_required, |
| 113 | + message=agent_message, |
| 114 | + timestamp=datetime.now(timezone.utc).isoformat(), |
| 115 | + ), |
| 116 | + final=True, |
| 117 | + ) |
| 118 | + await event_queue.enqueue_event(final_update) |
| 119 | + |
| 120 | + |
| 121 | + |
| 122 | +async def main(): |
| 123 | + HTTP_PORT = int(os.environ.get("HTTP_PORT", 41241)) |
| 124 | + |
| 125 | + # 1. Setup Executor and Handlers |
| 126 | + agent_executor = SUTAgentExecutor() |
| 127 | + task_store = InMemoryTaskStore() |
| 128 | + queue_manager = InMemoryQueueManager() |
| 129 | + |
| 130 | + request_handler = DefaultRequestHandler( |
| 131 | + task_store=task_store, |
| 132 | + queue_manager=queue_manager, |
| 133 | + agent_executor=agent_executor, |
| 134 | + ) |
| 135 | + |
| 136 | + # 2. Create Agent Card (JSON-RPC only) |
| 137 | + sut_agent_card = AgentCard( |
| 138 | + name="SUT Agent", |
| 139 | + description="A sample agent to be used as SUT against tck tests.", |
| 140 | + url=f"http://localhost:{HTTP_PORT}/a2a/jsonrpc", |
| 141 | + provider=AgentProvider( |
| 142 | + organization="A2A Samples", |
| 143 | + url="https://example.com/a2a-samples", |
| 144 | + ), |
| 145 | + version="1.0.0", |
| 146 | + protocol_version="0.3.0", |
| 147 | + capabilities=AgentCapabilities( |
| 148 | + streaming=True, |
| 149 | + push_notifications=False, |
| 150 | + state_transition_history=True, |
| 151 | + ), |
| 152 | + default_input_modes=["text"], |
| 153 | + default_output_modes=["text", "task-status"], |
| 154 | + skills=[ |
| 155 | + { |
| 156 | + "id": "sut_agent", |
| 157 | + "name": "SUT Agent", |
| 158 | + "description": "Simulate the general flow of a streaming agent.", |
| 159 | + "tags": ["sut"], |
| 160 | + "examples": ["hi", "hello world", "how are you", "goodbye"], |
| 161 | + "input_modes": ["text"], |
| 162 | + "output_modes": ["text", "task-status"], |
| 163 | + } |
| 164 | + ], |
| 165 | + supports_authenticated_extended_card=False, |
| 166 | + preferred_transport="JSONRPC", |
| 167 | + additional_interfaces=[ |
| 168 | + {"url": f"http://localhost:{HTTP_PORT}/a2a/jsonrpc", "transport": "JSONRPC"}, |
| 169 | + ], |
| 170 | + ) |
| 171 | + |
| 172 | + # 3. Setup HTTP App |
| 173 | + json_rpc_app = A2AFastAPIApplication( |
| 174 | + agent_card=sut_agent_card, |
| 175 | + http_handler=request_handler, |
| 176 | + ) |
| 177 | + app = json_rpc_app.build( |
| 178 | + rpc_url="/a2a/jsonrpc", |
| 179 | + agent_card_url="/.well-known/agent-card.json" |
| 180 | + ) |
| 181 | + |
| 182 | + logger.info(f"Starting HTTP server on port {HTTP_PORT}...") |
| 183 | + config = Config(app, host="0.0.0.0", port=HTTP_PORT, log_level="info") |
| 184 | + server = Server(config) |
| 185 | + |
| 186 | + await server.serve() |
| 187 | + |
| 188 | +if __name__ == "__main__": |
| 189 | + asyncio.run(main()) |
0 commit comments