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

100 lines
2.7 KiB
Python
Raw Normal View History

2026-03-09 17:32:11 +08:00
"""
Agent 管理 API 路由
接入 AgentRegistry 服务,提供 Agent 注册、查询、状态管理
2026-03-09 17:32:11 +08:00
"""
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional
from dataclasses import asdict
2026-03-09 17:32:11 +08:00
from ..services.agent_registry import get_agent_registry
2026-03-09 17:32:11 +08:00
router = APIRouter()
2026-03-09 17:32:11 +08:00
class AgentCreate(BaseModel):
agent_id: str
name: str
role: str = "developer"
model: str
description: Optional[str] = None
class AgentStateUpdate(BaseModel):
task: Optional[str] = ""
progress: Optional[int] = 0
working_files: Optional[list] = None
status: Optional[str] = "idle"
2026-03-09 17:32:11 +08:00
@router.get("")
2026-03-09 17:32:11 +08:00
@router.get("/")
async def list_agents():
"""获取所有 Agent 列表"""
registry = get_agent_registry()
agents = await registry.list_agents()
return {
"agents": [asdict(agent) for agent in agents]
}
2026-03-09 17:32:11 +08:00
@router.post("/register")
async def register_agent(agent: AgentCreate):
"""注册新 Agent"""
registry = get_agent_registry()
agent_info = await registry.register_agent(
agent_id=agent.agent_id,
name=agent.name,
role=agent.role,
model=agent.model,
description=agent.description or ""
)
return asdict(agent_info)
2026-03-09 17:32:11 +08:00
@router.get("/{agent_id}")
async def get_agent(agent_id: str):
"""获取指定 Agent 信息"""
registry = get_agent_registry()
agent_info = await registry.get_agent(agent_id)
if not agent_info:
raise HTTPException(status_code=404, detail="Agent not found")
return asdict(agent_info)
2026-03-09 17:32:11 +08:00
@router.delete("/{agent_id}")
async def delete_agent(agent_id: str):
"""删除 Agent"""
registry = get_agent_registry()
success = await registry.unregister_agent(agent_id)
if not success:
raise HTTPException(status_code=404, detail="Agent not found")
return {"message": "Agent deleted"}
2026-03-09 17:32:11 +08:00
@router.get("/{agent_id}/state")
async def get_agent_state(agent_id: str):
"""获取 Agent 状态"""
registry = get_agent_registry()
state = await registry.get_state(agent_id)
if not state:
raise HTTPException(status_code=404, detail="Agent state not found")
return asdict(state)
2026-03-09 17:32:11 +08:00
@router.post("/{agent_id}/state")
async def update_agent_state(agent_id: str, data: AgentStateUpdate):
2026-03-09 17:32:11 +08:00
"""更新 Agent 状态"""
registry = get_agent_registry()
agent_info = await registry.get_agent(agent_id)
if not agent_info:
raise HTTPException(status_code=404, detail="Agent not found")
await registry.update_state(
agent_id=agent_id,
task=data.task or "",
progress=data.progress or 0,
working_files=data.working_files
)
2026-03-09 17:32:11 +08:00
return {"success": True}