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