forked from a2aproject/a2a-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastapi_app.py
More file actions
101 lines (81 loc) · 3.33 KB
/
fastapi_app.py
File metadata and controls
101 lines (81 loc) · 3.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import logging
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from fastapi import APIRouter, FastAPI, Request, Response
_package_fastapi_installed = True
else:
try:
from fastapi import APIRouter, FastAPI, Request, Response
_package_fastapi_installed = True
except ImportError:
APIRouter = Any
FastAPI = Any
Request = Any
Response = Any
_package_fastapi_installed = False
from a2a.server.apps.jsonrpc.jsonrpc_app import CallContextBuilder
from a2a.server.apps.rest.rest_adapter import RESTAdapter
from a2a.server.request_handlers.request_handler import RequestHandler
from a2a.types import AgentCard
from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
logger = logging.getLogger(__name__)
class A2ARESTFastAPIApplication:
"""A FastAPI application implementing the A2A protocol server REST endpoints.
Handles incoming REST requests, routes them to the appropriate
handler methods, and manages response generation including Server-Sent Events
(SSE).
"""
def __init__(
self,
agent_card: AgentCard,
http_handler: RequestHandler,
context_builder: CallContextBuilder | None = None,
):
"""Initializes the A2ARESTFastAPIApplication.
Args:
agent_card: The AgentCard describing the agent's capabilities.
http_handler: The handler instance responsible for processing A2A
requests via http.
extended_agent_card: An optional, distinct AgentCard to be served
at the authenticated extended card endpoint.
context_builder: The CallContextBuilder used to construct the
ServerCallContext passed to the http_handler. If None, no
ServerCallContext is passed.
"""
if not _package_fastapi_installed:
raise ImportError(
'The `fastapi` package is required to use the'
' `A2ARESTFastAPIApplication`. It can be added as a part of'
' `a2a-sdk` optional dependencies, `a2a-sdk[http-server]`.'
)
self._adapter = RESTAdapter(
agent_card=agent_card,
http_handler=http_handler,
context_builder=context_builder,
)
def build(
self,
agent_card_url: str = AGENT_CARD_WELL_KNOWN_PATH,
rpc_url: str = '',
**kwargs: Any,
) -> FastAPI:
"""Builds and returns the FastAPI application instance.
Args:
agent_card_url: The URL for the agent card endpoint.
rpc_url: The URL for the A2A JSON-RPC endpoint.
extended_agent_card_url: The URL for the authenticated extended agent card endpoint.
**kwargs: Additional keyword arguments to pass to the FastAPI constructor.
Returns:
A configured FastAPI application instance.
"""
app = FastAPI(**kwargs)
router = APIRouter()
for route, callback in self._adapter.routes().items():
router.add_api_route(
f'{rpc_url}{route[0]}', callback, methods=[route[1]]
)
@router.get(f'{rpc_url}{agent_card_url}')
async def get_agent_card(request: Request) -> Response:
return await self._adapter.handle_get_agent_card(request)
app.include_router(router)
return app