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

65 lines
1.8 KiB
Python
Raw Normal View History

2026-03-09 17:32:11 +08:00
"""
心跳管理 API 路由
接入 HeartbeatService 服务,监控 Agent 活跃状态
2026-03-09 17:32:11 +08:00
"""
from fastapi import APIRouter
from pydantic import BaseModel
from typing import Optional
2026-03-09 17:32:11 +08:00
from ..services.heartbeat import get_heartbeat_service
2026-03-09 17:32:11 +08:00
router = APIRouter()
2026-03-09 17:32:11 +08:00
class HeartbeatUpdate(BaseModel):
status: str = "idle"
current_task: Optional[str] = ""
progress: Optional[int] = 0
2026-03-09 17:32:11 +08:00
@router.get("")
2026-03-09 17:32:11 +08:00
@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()
2026-03-09 17:32:11 +08:00
}
return {"heartbeats": heartbeats}
2026-03-09 17:32:11 +08:00
@router.post("/{agent_id}")
async def update_heartbeat(agent_id: str, data: HeartbeatUpdate = None):
2026-03-09 17:32:11 +08:00
"""更新 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
)
2026-03-09 17:32:11 +08:00
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)
}