Files

177 lines
6.8 KiB
Python

"""The A2A server: JSON-RPC at /a2a, the agent card, health, and pre-approved /generate.
Run with: python -m execution_engine.main
"""
from __future__ import annotations
import logging
from collections.abc import AsyncIterator, Callable
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from pathlib import Path
import click
import uvicorn
from a2a.server.request_handlers.default_request_handler_v2 import (
DefaultRequestHandlerV2,
)
from a2a.server.routes.jsonrpc_routes import create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore
from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from execution_engine.a2a_server import EngineExecutor
from execution_engine.agent import Assembly, open_assembly
from execution_engine.card import A2A_PATH, build_agent_card, card_document
from execution_engine.config import Settings, get_settings
from execution_engine.presentation import generate_response
from execution_engine.providers import ProviderBundle
from execution_engine.workflows.workflow import Workflow
logger = logging.getLogger(__name__)
AssemblyFactory = Callable[[Settings], AbstractAsyncContextManager[Assembly]]
LEGACY_CARD_PATH = "/.well-known/agent.json"
WorkflowBuilder = Callable[[Settings, ProviderBundle], Workflow]
def create_app(
workflow: Workflow,
settings: Settings | None = None,
assembly_factory: AssemblyFactory | None = None,
*,
root: Path | None = None,
build: WorkflowBuilder | None = None,
) -> Starlette:
"""The agent's server. `root` is the agent's own folder (see `open_assembly`);
it is needed unless `assembly_factory` builds the assembly some other way.
`build`, when given, makes the Workflow that is assembled from the settings and
the provider bundle; the card describes `workflow`."""
settings = settings or get_settings()
card = build_agent_card(settings, workflow)
served_card = card_document(card, workflow)
if assembly_factory is None:
if root is None:
raise ValueError("create_app needs the agent's root or an assembly factory")
agent_root = root
def assembly_factory(given: Settings) -> AbstractAsyncContextManager[Assembly]:
return open_assembly(given, build or workflow, root=agent_root)
open_agent = assembly_factory
async def agent_card(request: Request) -> JSONResponse:
return JSONResponse(served_card)
async def health(request: Request) -> JSONResponse:
assembly: Assembly = request.app.state.assembly
return JSONResponse(
{
"status": "healthy",
"agent": settings.AGENT_NAME,
"version": settings.AGENT_VERSION,
"cloud_provider": assembly.bundle.name,
"mcp_discovery_gaps": assembly.mcp_gaps,
}
)
async def generate(request: Request) -> JSONResponse:
"""Pre-approved, one-shot Execution for batch and evaluation callers."""
assembly: Assembly = request.app.state.assembly
try:
body = await request.json()
except ValueError:
body = {}
workflow_request = str(body.get("request") or "").strip()
if not workflow_request and not body.get("scope") and not body.get("sources"):
return JSONResponse(
{"error": "'request' or a 'scope' spec is required"}, status_code=400
)
try:
interaction = await assembly.engine.start(
workflow_request,
session_id=body.get("session_id"),
customer_case=body.get("customer_case"),
baseline=body.get("baseline"),
overlay_skills=body.get("overlay_skills") or (),
**{
name: body[name]
for name in assembly.engine.workflow.options
if name in body
},
scope=body.get("scope"),
sources=body.get("sources"),
pre_approved=True,
allow_cloud_read=bool(body.get("allow_cloud_read", False)),
)
except ValueError as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
except Exception as exc:
logger.exception("/generate failed")
return JSONResponse(
{"error": f"{type(exc).__name__}: {exc}"}, status_code=500
)
respond = assembly.engine.workflow.response
return JSONResponse(
respond(interaction, assembly.roles)
if respond
else generate_response(interaction)
)
@asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[None]:
async with open_agent(settings) as assembly:
handler = DefaultRequestHandlerV2(
agent_executor=EngineExecutor(
assembly.engine, assembly.intake, assembly.answers
),
task_store=InMemoryTaskStore(),
agent_card=card,
)
app.state.assembly = assembly
app.state.request_handler = handler
# The card names /a2a. The root serves the same handler, because the
# KAB platform calls the URL an agent was registered with rather
# than the interface its card names.
for path in (A2A_PATH, "/"):
app.router.routes.extend(
create_jsonrpc_routes(handler, path, enable_v0_3_compat=True)
)
try:
yield
finally:
await handler.aclose()
return Starlette(
routes=[
Route("/health", health, methods=["GET"]),
Route("/generate", generate, methods=["POST"]),
Route(AGENT_CARD_WELL_KNOWN_PATH, agent_card, methods=["GET"]),
Route(LEGACY_CARD_PATH, agent_card, methods=["GET"]),
],
lifespan=lifespan,
)
def serve(workflow: Workflow, root: Path, build: WorkflowBuilder | None = None) -> None:
"""Serve an agent over A2A: the entrypoint an agent's own `main` calls. An
agent whose Workflow depends on its settings or provider bundle gives `build`."""
@click.command()
@click.option("--host", default=None, help="Host to bind (default A2A_HOST)")
@click.option("--port", default=None, type=int, help="Port (default A2A_PORT)")
def main(host: str | None, port: int | None) -> None:
settings = get_settings()
logging.basicConfig(level=settings.LOG_LEVEL.upper())
uvicorn.run(
create_app(workflow, settings, root=root, build=build),
host=host or settings.A2A_HOST,
port=port or settings.A2A_PORT,
)
main()