Files
multiAgentTry/backend/app/routers/heartbeats.py

65 lines
1.8 KiB
Python
Raw Normal View History

"""
心跳管理 API 路由
接入 HeartbeatService 服务监控 Agent 活跃状态
"""
from fastapi import APIRouter
from pydantic import BaseModel
from typing import Optional
from ..services.heartbeat import get_heartbeat_service
router = APIRouter()
class HeartbeatUpdate(BaseModel):
status: str = "idle"
current_task: Optional[str] = ""
progress: Optional[int] = 0
@router.get("")
@router.get("/")
async def list_heartbeats():
"""获取所有 Agent 心跳"""
service = get_heartbeat_service()
all_hb = await service.get_all_heartbeats()
heartbeats = {}
for agent_id, hb in all_hb.items():
heartbeats[agent_id] = {
"agent_id": hb.agent_id,
"last_heartbeat": hb.last_heartbeat,
"status": hb.status,
"current_task": hb.current_task,
"progress": hb.progress,
"elapsed_display": hb.elapsed_display,
"is_timeout": hb.is_timeout()
}
return {"heartbeats": heartbeats}
@router.post("/{agent_id}")
async def update_heartbeat(agent_id: str, data: HeartbeatUpdate = None):
"""更新 Agent 心跳"""
service = get_heartbeat_service()
if data is None:
data = HeartbeatUpdate()
await service.update_heartbeat(
agent_id=agent_id,
status=data.status,
current_task=data.current_task or "",
progress=data.progress or 0
)
return {"success": True}
@router.get("/timeouts")
async def check_timeouts(timeout_seconds: int = 60):
"""检查超时的 Agent"""
service = get_heartbeat_service()
timeout_agents = await service.check_timeout(timeout_seconds)
return {
"timeout_seconds": timeout_seconds,
"timeout_agents": timeout_agents,
"count": len(timeout_agents)
}