File size: 24,271 Bytes
f0df9cb | 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 | # Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Shared A2A protocol handler for demo agents.
Provides a factory function that creates a FastAPI app implementing the
Google A2A (Agent-to-Agent) protocol with:
- GET /.well-known/agent-card.json -- agent card discovery
- POST / -- JSON-RPC 2.0 dispatch
"""
from __future__ import annotations
import logging
import os
import uuid
from dataclasses import dataclass, field
# Ensure Ollama uses 127.0.0.1 to avoid DNS/async resolution issues with litellm
if not os.environ.get("OLLAMA_API_BASE"):
os.environ["OLLAMA_API_BASE"] = "http://127.0.0.1:11434"
from datetime import datetime, timezone
from typing import Any, AsyncGenerator, Callable, Awaitable
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse
# ---------------------------------------------------------------------------
# Types used by handler functions
# ---------------------------------------------------------------------------
class MessagePart:
"""Lightweight mirror of the marketplace MessagePart schema."""
def __init__(self, type: str, content: str | None = None, data: dict | None = None, mime_type: str | None = None, text: str | None = None):
self.type = type
# A2A spec uses "text"; our internal convention uses "content". Accept both.
self.content = content or text
self.data = data
self.mime_type = mime_type
def to_dict(self) -> dict:
d: dict[str, Any] = {"type": self.type}
if self.content is not None:
d["content"] = self.content
if self.data is not None:
d["data"] = self.data
if self.mime_type is not None:
d["mime_type"] = self.mime_type
return d
class TaskMessage:
def __init__(self, role: str, parts: list[MessagePart]):
self.role = role
self.parts = parts
@classmethod
def from_dict(cls, d: dict) -> "TaskMessage":
parts = [MessagePart(**p) for p in d.get("parts", [])]
return cls(role=d["role"], parts=parts)
def to_dict(self) -> dict:
return {"role": self.role, "parts": [p.to_dict() for p in self.parts]}
class Artifact:
def __init__(
self,
name: str | None = None,
parts: list[MessagePart] | None = None,
metadata: dict | None = None,
ui_components: list[dict] | None = None,
):
self.name = name
self.parts = parts or []
self.metadata = metadata or {}
self.ui_components = ui_components or []
def to_dict(self) -> dict:
d = {
"name": self.name,
"parts": [p.to_dict() for p in self.parts],
"metadata": self.metadata,
}
if self.ui_components:
d["ui_components"] = self.ui_components
return d
# ---------------------------------------------------------------------------
# A2UI helpers β create structured UI components for rich rendering
# ---------------------------------------------------------------------------
def emit_table(title: str, headers: list[str], rows: list[list], caption: str | None = None) -> dict:
"""Create a table UI component."""
return {"type": "table", "title": title, "data": {"headers": headers, "rows": rows, "caption": caption}, "metadata": {}}
def emit_chart(title: str, chart_type: str, labels: list[str], datasets: list[dict]) -> dict:
"""Create a chart UI component (bar, line, pie, area)."""
return {"type": "chart", "title": title, "data": {"chart_type": chart_type, "labels": labels, "datasets": datasets}, "metadata": {}}
def emit_code(code: str, language: str, filename: str | None = None, title: str | None = None) -> dict:
"""Create a syntax-highlighted code block UI component."""
return {"type": "code_block", "title": title or filename, "data": {"code": code, "language": language, "filename": filename}, "metadata": {}}
def emit_diff(before: str, after: str, language: str | None = None, title: str | None = None) -> dict:
"""Create a side-by-side diff UI component."""
return {"type": "diff", "title": title, "data": {"before": before, "after": after, "language": language}, "metadata": {}}
def emit_image(url: str, alt: str | None = None, title: str | None = None) -> dict:
"""Create an image UI component."""
return {"type": "image", "title": title, "data": {"url": url, "alt": alt}, "metadata": {}}
# Handler signature:
# async def handler(skill_id: str, messages: list[TaskMessage]) -> list[Artifact]
HandlerFunc = Callable[[str, list[TaskMessage]], Awaitable[list[Artifact]]]
# ---------------------------------------------------------------------------
# AG-UI Streaming types
# ---------------------------------------------------------------------------
@dataclass
class StreamChunk:
"""A single chunk emitted by a streaming agent handler.
Types:
- "thinking" β agent reasoning (shown collapsed in UI)
- "text" β partial text output (appended progressively)
- "artifact" β complete artifact (rendered when received)
- "status" β status change (e.g. "working")
- "error" β error message
- "done" β final signal with optional artifact list
"""
type: str # thinking | text | artifact | status | error | done
content: str = ""
artifact: Artifact | None = None
artifacts: list[Artifact] | None = None # used with "done" to send all final artifacts
metadata: dict = field(default_factory=dict)
def to_sse(self) -> str:
"""Serialize to SSE event format."""
import json
data: dict[str, Any] = {"type": self.type}
if self.content:
data["content"] = self.content
if self.artifact:
data["artifact"] = self.artifact.to_dict()
if self.artifacts:
data["artifacts"] = [a.to_dict() for a in self.artifacts]
if self.metadata:
data["metadata"] = self.metadata
return f"event: {self.type}\ndata: {json.dumps(data)}\n\n"
# Streaming handler signature β yields StreamChunks instead of returning artifacts
StreamingHandlerFunc = Callable[
[str, list[TaskMessage]],
AsyncGenerator[StreamChunk, None],
]
logger = logging.getLogger(__name__)
async def _ollama_call(
model_name: str,
system_prompt: str,
user_message: str,
) -> str:
"""Call Ollama directly via httpx (bypasses LiteLLM async issues)."""
import httpx
base = os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434")
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message},
]
# connect quickly, but allow up to 5min for generation on slow hardware
timeout = httpx.Timeout(connect=10.0, read=300.0, write=10.0, pool=10.0)
async with httpx.AsyncClient(timeout=timeout) as client:
resp = await client.post(
f"{base}/api/chat",
json={"model": model_name, "messages": messages, "stream": False},
)
resp.raise_for_status()
return resp.json()["message"]["content"]
# ---------------------------------------------------------------------------
# Multi-provider LLM Router (built once at import time)
# ---------------------------------------------------------------------------
# Provider definitions: (env_var, model_string, rpm_limit)
_PROVIDER_DEFS = [
("GROQ_API_KEY", "groq/llama-3.3-70b-versatile", 30),
("CEREBRAS_API_KEY", "cerebras/llama-3.3-70b", 30),
("SAMBANOVA_API_KEY", "sambanova/Meta-Llama-3.3-70B-Instruct", 20),
("GEMINI_API_KEY", "gemini/gemini-2.0-flash", 15),
]
_router = None # Lazy-initialized on first call
def _build_router():
"""Build a LiteLLM Router from available API keys. Returns None if no keys."""
try:
from litellm import Router
except ImportError:
return None
model_list = []
for env_var, model_str, rpm in _PROVIDER_DEFS:
key = os.environ.get(env_var)
if key:
model_list.append({
"model_name": "agent-llm",
"litellm_params": {
"model": model_str,
"api_key": key,
"rpm": rpm,
},
})
if not model_list:
return None
providers = [m["litellm_params"]["model"] for m in model_list]
logger.info("LLM Router initialized with %d providers: %s", len(model_list), providers)
return Router(
model_list=model_list,
num_retries=2,
timeout=30,
allowed_fails=3,
cooldown_time=60,
retry_after=1,
)
async def llm_call(
system_prompt: str,
user_message: str,
model: str | None = None,
) -> str:
"""Call an LLM with automatic multi-provider fallback.
Uses LiteLLM Router to load-balance across available providers and
automatically retry on 429/500 errors. Falls back to single-model
call if MODEL env var is set explicitly, or echo if nothing works.
"""
global _router
explicit_model = model or os.environ.get("MODEL")
# Ollama: bypass router entirely
if explicit_model and explicit_model.lower().startswith("ollama/"):
try:
return await _ollama_call(explicit_model.split("/", 1)[1], system_prompt, user_message)
except Exception as exc:
logger.warning("Ollama call failed: %s: %s", type(exc).__name__, exc)
return f"[LLM unavailable β echoing input]\n\n{user_message}"
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message},
]
# Try Router first (multi-provider with automatic failover)
if _router is None:
_router = _build_router() or False # False = no keys available
if _router:
try:
response = await _router.acompletion(model="agent-llm", messages=messages)
return response.choices[0].message.content
except Exception as exc:
logger.warning("Router call failed: %s: %s", type(exc).__name__, exc)
# Fallback: direct single-model call (if MODEL env var set)
if explicit_model:
try:
import litellm
response = await litellm.acompletion(
model=explicit_model, messages=messages, timeout=60,
)
return response.choices[0].message.content
except Exception as exc:
logger.warning("Direct LLM call failed (%s): %s: %s", explicit_model, type(exc).__name__, exc)
return f"[LLM unavailable β echoing input]\n\n{user_message}"
async def llm_call_streaming(
system_prompt: str,
user_message: str,
model: str | None = None,
) -> AsyncGenerator[str, None]:
"""Streaming version of llm_call β yields text chunks as they arrive.
Falls back to non-streaming llm_call if streaming is unavailable.
"""
global _router
explicit_model = model or os.environ.get("MODEL")
# Ollama: stream via httpx
if explicit_model and explicit_model.lower().startswith("ollama/"):
import httpx
base = os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434")
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message},
]
timeout = httpx.Timeout(connect=10.0, read=300.0, write=10.0, pool=10.0)
async with httpx.AsyncClient(timeout=timeout) as client:
async with client.stream(
"POST",
f"{base}/api/chat",
json={"model": explicit_model.split("/", 1)[1], "messages": messages, "stream": True},
) as resp:
resp.raise_for_status()
import json
async for line in resp.aiter_lines():
if line.strip():
try:
chunk = json.loads(line)
content = chunk.get("message", {}).get("content", "")
if content:
yield content
except (ValueError, KeyError):
pass
return
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message},
]
# Try Router streaming first
if _router is None:
_router = _build_router() or False
if _router:
try:
response = await _router.acompletion(
model="agent-llm", messages=messages, stream=True,
)
async for chunk in response:
delta = chunk.choices[0].delta
if delta and delta.content:
yield delta.content
return
except Exception as exc:
logger.warning("Router streaming failed: %s: %s", type(exc).__name__, exc)
# Fallback: direct single-model streaming
if explicit_model:
try:
import litellm
response = await litellm.acompletion(
model=explicit_model, messages=messages, timeout=60, stream=True,
)
async for chunk in response:
delta = chunk.choices[0].delta
if delta and delta.content:
yield delta.content
return
except Exception as exc:
logger.warning("Direct LLM streaming failed (%s): %s: %s", explicit_model, type(exc).__name__, exc)
# Last resort: yield the full non-streaming response as one chunk
result = await llm_call(system_prompt, user_message, model)
yield result
# In-memory task store shared within one process
_task_store: dict[str, dict] = {}
# ---------------------------------------------------------------------------
# Factory
# ---------------------------------------------------------------------------
def create_a2a_app(
name: str,
description: str,
version: str,
skills: list[dict],
handler_func: HandlerFunc,
port: int,
credits_per_task: float = 1,
streaming_handler_func: StreamingHandlerFunc | None = None,
) -> FastAPI:
"""Create a FastAPI app that speaks the A2A protocol.
Parameters
----------
name:
Human-readable agent name.
description:
Short description shown in the agent card.
version:
Semantic version string.
skills:
List of skill dicts following the A2A agent-card skill schema.
handler_func:
Async callable ``(skill_id, messages) -> list[Artifact]``.
port:
Port number the agent listens on (used for the agent card URL).
credits_per_task:
Credit cost advertised for every task handled by this agent.
streaming_handler_func:
Optional async generator ``(skill_id, messages) -> StreamChunk``.
When provided, the agent advertises ``streaming: true`` in its card
and supports the ``tasks/sendSubscribe`` SSE method.
"""
supports_streaming = streaming_handler_func is not None
app = FastAPI(title=name, version=version)
# -- Agent card -----------------------------------------------------------
# Use AGENT_URL env var when deployed (e.g. HF Spaces), else localhost
base_url = os.environ.get("AGENT_URL", f"http://localhost:{port}")
agent_card = {
"name": name,
"description": description,
"url": base_url,
"version": version,
"capabilities": {
"streaming": supports_streaming,
"pushNotifications": False,
"stateTransitionHistory": False,
},
"skills": skills,
"securitySchemes": [],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"pricing": {
"model": "per_task",
"credits": credits_per_task,
},
}
@app.get("/.well-known/agent-card.json")
async def get_agent_card():
return agent_card
# -- JSON-RPC 2.0 dispatch -----------------------------------------------
@app.post("/")
async def jsonrpc_dispatch(request: Request):
body = await request.json()
jsonrpc = body.get("jsonrpc", "2.0")
method = body.get("method")
params = body.get("params", {})
req_id = body.get("id")
if method == "tasks/send":
return await _handle_send(params, req_id, jsonrpc)
elif method == "tasks/get":
return await _handle_get(params, req_id, jsonrpc)
elif method == "tasks/cancel":
return await _handle_cancel(params, req_id, jsonrpc)
elif method == "tasks/sendSubscribe":
return await _handle_send_subscribe(params, req_id, jsonrpc)
else:
return _error_response(req_id, -32601, f"Method not found: {method}", jsonrpc)
# -- tasks/send -----------------------------------------------------------
async def _handle_send(params: dict, req_id: Any, jsonrpc: str):
try:
task_id = params.get("id") or str(uuid.uuid4())
metadata = params.get("metadata", {})
skill_id = params.get("skill_id") or metadata.get("skill_id") or _default_skill_id()
raw_messages = params.get("message", params.get("messages", []))
# Accept a single message dict or a list of messages
if isinstance(raw_messages, dict):
raw_messages = [raw_messages]
messages = [TaskMessage.from_dict(m) for m in raw_messages]
# Resolve skill_id from first message if caller put it there
if not skill_id:
skill_id = _default_skill_id()
# Execute
artifacts = await handler_func(skill_id, messages)
task = {
"id": task_id,
"status": {"state": "completed"},
"messages": [m.to_dict() for m in messages],
"artifacts": [a.to_dict() for a in artifacts],
"metadata": {
"credits_charged": credits_per_task,
"completed_at": datetime.now(timezone.utc).isoformat(),
},
}
_task_store[task_id] = task
return JSONResponse(content={
"jsonrpc": jsonrpc,
"id": req_id,
"result": task,
})
except Exception as exc:
return _error_response(req_id, -32000, str(exc), jsonrpc)
# -- tasks/sendSubscribe (AG-UI streaming) --------------------------------
async def _handle_send_subscribe(params: dict, req_id: Any, jsonrpc: str):
"""Stream task execution via Server-Sent Events.
If a streaming_handler_func was provided, yields chunks in real-time.
Otherwise falls back to running handler_func and emitting the result
as a single artifact event.
"""
import json as _json
task_id = params.get("id") or str(uuid.uuid4())
metadata = params.get("metadata", {})
skill_id = params.get("skill_id") or metadata.get("skill_id") or _default_skill_id()
raw_messages = params.get("message", params.get("messages", []))
if isinstance(raw_messages, dict):
raw_messages = [raw_messages]
messages = [TaskMessage.from_dict(m) for m in raw_messages]
async def _stream_generator():
# Emit initial status
yield StreamChunk(type="status", content="working").to_sse()
try:
if streaming_handler_func is not None:
# True streaming β yield each chunk from the handler
final_artifacts: list[Artifact] = []
accumulated_text = ""
async for chunk in streaming_handler_func(skill_id, messages):
yield chunk.to_sse()
# Track artifacts for final task store
if chunk.type == "artifact" and chunk.artifact:
final_artifacts.append(chunk.artifact)
elif chunk.type == "text":
accumulated_text += chunk.content
elif chunk.type == "done" and chunk.artifacts:
final_artifacts = chunk.artifacts
# If no explicit artifacts were emitted, create one from accumulated text
if not final_artifacts and accumulated_text:
final_artifacts = [Artifact(
name="response",
parts=[MessagePart(type="text", content=accumulated_text)],
metadata={"skill": skill_id, "streamed": True},
)]
# Emit done with final artifacts
done_chunk = StreamChunk(
type="done",
artifacts=final_artifacts,
metadata={"credits_charged": credits_per_task},
)
yield done_chunk.to_sse()
else:
# Non-streaming fallback β run handler, emit result as single event
artifacts = await handler_func(skill_id, messages)
for artifact in artifacts:
yield StreamChunk(type="artifact", artifact=artifact).to_sse()
yield StreamChunk(
type="done",
artifacts=artifacts,
metadata={"credits_charged": credits_per_task},
).to_sse()
except Exception as exc:
logger.exception("Streaming handler error")
yield StreamChunk(type="error", content=str(exc)).to_sse()
# Store final task
task = {
"id": task_id,
"status": {"state": "completed"},
"messages": [m.to_dict() for m in messages],
"artifacts": [a.to_dict() for a in (final_artifacts if streaming_handler_func else artifacts)],
"metadata": {
"credits_charged": credits_per_task,
"completed_at": datetime.now(timezone.utc).isoformat(),
},
}
_task_store[task_id] = task
return StreamingResponse(
_stream_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
# -- tasks/get ------------------------------------------------------------
async def _handle_get(params: dict, req_id: Any, jsonrpc: str):
task_id = params.get("id")
task = _task_store.get(task_id)
if task is None:
return _error_response(req_id, -32001, f"Task not found: {task_id}", jsonrpc)
return JSONResponse(content={
"jsonrpc": jsonrpc,
"id": req_id,
"result": task,
})
# -- tasks/cancel ---------------------------------------------------------
async def _handle_cancel(params: dict, req_id: Any, jsonrpc: str):
task_id = params.get("id")
task = _task_store.get(task_id)
if task is None:
return _error_response(req_id, -32001, f"Task not found: {task_id}", jsonrpc)
task["status"] = {"state": "canceled"}
return JSONResponse(content={
"jsonrpc": jsonrpc,
"id": req_id,
"result": task,
})
# -- helpers --------------------------------------------------------------
def _default_skill_id() -> str:
if skills:
return skills[0]["id"]
return "default"
def _error_response(req_id: Any, code: int, message: str, jsonrpc: str = "2.0"):
return JSONResponse(content={
"jsonrpc": jsonrpc,
"id": req_id,
"error": {"code": code, "message": message},
})
return app
|