|
1 | 1 | import logging
|
2 | 2 |
|
3 |
| -from collections.abc import AsyncIterator |
4 |
| -from contextlib import asynccontextmanager |
5 | 3 | from typing import Any
|
6 | 4 |
|
7 | 5 | from fastapi import FastAPI
|
|
21 | 19 | logger = logging.getLogger(__name__)
|
22 | 20 |
|
23 | 21 |
|
| 22 | +class A2AFastAPI(FastAPI): |
| 23 | + """A FastAPI application that adds A2A-specific OpenAPI components.""" |
| 24 | + |
| 25 | + _a2a_components_added: bool = False |
| 26 | + |
| 27 | + def openapi(self) -> dict[str, Any]: |
| 28 | + """Generates the OpenAPI schema for the application.""" |
| 29 | + openapi_schema = super().openapi() |
| 30 | + if not self._a2a_components_added: |
| 31 | + a2a_request_schema = A2ARequest.model_json_schema( |
| 32 | + ref_template='#/components/schemas/{model}' |
| 33 | + ) |
| 34 | + defs = a2a_request_schema.pop('$defs', {}) |
| 35 | + component_schemas = openapi_schema.setdefault( |
| 36 | + 'components', {} |
| 37 | + ).setdefault('schemas', {}) |
| 38 | + component_schemas.update(defs) |
| 39 | + component_schemas['A2ARequest'] = a2a_request_schema |
| 40 | + self._a2a_components_added = True |
| 41 | + return openapi_schema |
| 42 | + |
| 43 | + |
24 | 44 | class A2AFastAPIApplication(JSONRPCApplication):
|
25 | 45 | """A FastAPI application implementing the A2A protocol server endpoints.
|
26 | 46 |
|
@@ -92,23 +112,7 @@ def build(
|
92 | 112 | Returns:
|
93 | 113 | A configured FastAPI application instance.
|
94 | 114 | """
|
95 |
| - |
96 |
| - @asynccontextmanager |
97 |
| - async def lifespan(app: FastAPI) -> AsyncIterator[None]: |
98 |
| - a2a_request_schema = A2ARequest.model_json_schema( |
99 |
| - ref_template='#/components/schemas/{model}' |
100 |
| - ) |
101 |
| - defs = a2a_request_schema.pop('$defs', {}) |
102 |
| - openapi_schema = app.openapi() |
103 |
| - component_schemas = openapi_schema.setdefault( |
104 |
| - 'components', {} |
105 |
| - ).setdefault('schemas', {}) |
106 |
| - component_schemas.update(defs) |
107 |
| - component_schemas['A2ARequest'] = a2a_request_schema |
108 |
| - |
109 |
| - yield |
110 |
| - |
111 |
| - app = FastAPI(lifespan=lifespan, **kwargs) |
| 115 | + app = A2AFastAPI(**kwargs) |
112 | 116 |
|
113 | 117 | self.add_routes_to_app(
|
114 | 118 | app, agent_card_url, rpc_url, extended_agent_card_url
|
|
0 commit comments