|
| 1 | +# from typing import TYPE_CHECKING |
| 2 | + |
| 3 | +import inspect |
| 4 | + |
| 5 | +from aiohttp import web |
| 6 | +from aiohttp.web_request import Request |
| 7 | + |
| 8 | +from besser.agent.exceptions.logger import logger |
| 9 | +from besser.agent.platforms.a2a.error_handler import JSONRPCError, MethodNotFound, InvalidParams, TaskError |
| 10 | +from besser.agent.platforms.a2a.error_handler import INTERNAL_ERROR, PARSE_ERROR, INVALID_REQUEST, TASK_PENDING, TASK_FAILED, TASK_NOT_FOUND |
| 11 | +from besser.agent.platforms.a2a.agent_registry import AgentRegistry |
| 12 | +# if TYPE_CHECKING: |
| 13 | +# from besser.agent.platforms.a2a.a2a_platform import A2APlatform |
| 14 | + |
| 15 | +class A2ARouter: |
| 16 | + def __init__(self) -> None: |
| 17 | + self.methods = {} |
| 18 | + |
| 19 | + def register(self, method_name, func) -> None: |
| 20 | + ''' |
| 21 | + Register a method (coupled to its name, also called as key) that can be called via RPC. |
| 22 | + ''' |
| 23 | + self.methods[method_name] = func |
| 24 | + |
| 25 | + async def handle(self, method_name: str, params: dict) -> web.json_response: |
| 26 | + """ |
| 27 | + Execute the method given its name and parameters |
| 28 | + """ |
| 29 | + |
| 30 | + if method_name not in self.methods: |
| 31 | + logger.error(f"Method '{method_name}' not found") |
| 32 | + raise MethodNotFound(message=f"Method '{method_name}' not found") |
| 33 | + |
| 34 | + if not isinstance(params, dict): |
| 35 | + logger.error(f"Params must be a dictionary") |
| 36 | + raise InvalidParams() |
| 37 | + |
| 38 | + method = self.methods[method_name] |
| 39 | + |
| 40 | + # for handling async tasks, else it is sync |
| 41 | + if inspect.iscoroutinefunction(method): |
| 42 | + return await method(**params) |
| 43 | + else: |
| 44 | + return method(**params) |
| 45 | + |
| 46 | + async def aiohttp_handler(self, request: Request) -> web.json_response: |
| 47 | + """ |
| 48 | + Handle HTTP requests from the server |
| 49 | + """ |
| 50 | + request_id = None |
| 51 | + try: |
| 52 | + body = await request.json() |
| 53 | + request_id = body.get("id") |
| 54 | + except Exception: |
| 55 | + logger.error(PARSE_ERROR) |
| 56 | + return web.json_response({ |
| 57 | + "jsonrpc": "2.0", |
| 58 | + "error": PARSE_ERROR, |
| 59 | + "id": request_id |
| 60 | + }) |
| 61 | + |
| 62 | + if "method" not in body or not isinstance(body["method"], str): |
| 63 | + logger.error(INVALID_REQUEST) |
| 64 | + return web.json_response({ |
| 65 | + "jsonrpc": "2.0", |
| 66 | + "error": INVALID_REQUEST, |
| 67 | + "id": body.get("id") |
| 68 | + }) |
| 69 | + |
| 70 | + method = body['method'] |
| 71 | + params = body.get('params', {}) |
| 72 | + |
| 73 | + try: |
| 74 | + result = await self.handle(method, params) |
| 75 | + return web.json_response({ |
| 76 | + "jsonrpc": "2.0", |
| 77 | + "result": result, |
| 78 | + "id": request_id |
| 79 | + }) |
| 80 | + except JSONRPCError as e: |
| 81 | + return web.json_response({ |
| 82 | + "jsonrpc": "2.0", |
| 83 | + "error": {"code": e.code, "message": e.message}, |
| 84 | + "id": request_id |
| 85 | + }) |
| 86 | + |
| 87 | + except TaskError as e: |
| 88 | + error_map = { |
| 89 | + "TASK_PENDING": TASK_PENDING, |
| 90 | + "TASK_FAILED": TASK_FAILED, |
| 91 | + "TASK_NOT_FOUND": TASK_NOT_FOUND |
| 92 | + } |
| 93 | + logger.error(error_map.get(e.code, INTERNAL_ERROR)) |
| 94 | + return web.json_response({ |
| 95 | + "jsonrpc": "2.0", |
| 96 | + "error": error_map.get(e.code, INTERNAL_ERROR), |
| 97 | + "id": request_id |
| 98 | + }) |
| 99 | + except Exception as e: |
| 100 | + # print(f"Error: \n{e}") |
| 101 | + logger.error(f"Internal error: {str(e)}") |
| 102 | + return web.json_response({ |
| 103 | + "jsonrpc": "2.0", |
| 104 | + "error": {**INTERNAL_ERROR, |
| 105 | + "message": str(e)}, |
| 106 | + "id": request_id |
| 107 | + }) |
| 108 | + |
| 109 | + def register_task_methods(self, platform: 'A2APlatform') -> None: |
| 110 | + """ |
| 111 | + Auto-register internal methods for creating, executing and getting task status. |
| 112 | + """ |
| 113 | + self.register("create_task_and_run", platform.rpc_create_task) |
| 114 | + self.register("task_create", platform.create_task) |
| 115 | + self.register("task_status", platform.get_status) |
| 116 | + |
| 117 | + # |
| 118 | + def register_orchestration_methods(self, platform: 'A2APlatform', registry: AgentRegistry) -> None: |
| 119 | + """ |
| 120 | + Register methods used for orchestration in its router. Enables one agent to call another agent. |
| 121 | + """ |
| 122 | + async def call_agent_rpc(target_agent_id: str, method: str, params: dict): |
| 123 | + return await platform.rpc_call_agent(target_agent_id, method, params, registry) |
| 124 | + |
| 125 | + self.register("call_agent", call_agent_rpc) |
0 commit comments