76 lines
2.6 KiB
Python
76 lines
2.6 KiB
Python
"""智能体路由:我的 + 内置/公开市场,CRUD。"""
|
|
import json
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..core.deps import get_current_user
|
|
from ..core.response import ok
|
|
from ..database import get_db
|
|
from ..models import Agent, User
|
|
from ..schemas.agent import AgentCreate, AgentUpdate
|
|
|
|
router = APIRouter(prefix="/agents", tags=["智能体"])
|
|
|
|
|
|
def _agent_out(a: Agent) -> dict:
|
|
try:
|
|
tools = json.loads(a.tools) if a.tools else []
|
|
except json.JSONDecodeError:
|
|
tools = []
|
|
return {
|
|
"id": a.id, "user_id": a.user_id, "name": a.name, "description": a.description,
|
|
"avatar": a.avatar, "system_prompt": a.system_prompt, "model": a.model,
|
|
"temperature": a.temperature, "tools": tools, "is_public": a.is_public,
|
|
"is_builtin": a.is_builtin, "created_at": a.created_at.isoformat(),
|
|
}
|
|
|
|
|
|
@router.get("")
|
|
def list_agents(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
|
"""自己的 + 公开/内置的智能体。"""
|
|
agents = (
|
|
db.query(Agent)
|
|
.filter((Agent.user_id == user.id) | (Agent.is_public.is_(True)))
|
|
.order_by(Agent.is_builtin.desc(), Agent.id).all()
|
|
)
|
|
return ok([_agent_out(a) for a in agents])
|
|
|
|
|
|
@router.post("")
|
|
def create_agent(body: AgentCreate, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
|
a = Agent(**body.model_dump(exclude={"tools"}), tools=json.dumps(body.tools, ensure_ascii=False),
|
|
user_id=user.id)
|
|
db.add(a)
|
|
db.commit()
|
|
db.refresh(a)
|
|
return ok(_agent_out(a))
|
|
|
|
|
|
@router.put("/{agent_id}")
|
|
def update_agent(agent_id: int, body: AgentUpdate,
|
|
user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
|
a = db.get(Agent, agent_id)
|
|
if not a or (a.user_id and a.user_id != user.id):
|
|
raise HTTPException(status_code=404, detail="智能体不存在")
|
|
data = body.model_dump(exclude_unset=True)
|
|
if "tools" in data:
|
|
data["tools"] = json.dumps(data["tools"], ensure_ascii=False)
|
|
for k, v in data.items():
|
|
setattr(a, k, v)
|
|
db.commit()
|
|
db.refresh(a)
|
|
return ok(_agent_out(a))
|
|
|
|
|
|
@router.delete("/{agent_id}")
|
|
def delete_agent(agent_id: int, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
|
a = db.get(Agent, agent_id)
|
|
if not a or (a.user_id and a.user_id != user.id):
|
|
raise HTTPException(status_code=404, detail="智能体不存在")
|
|
if a.is_builtin:
|
|
raise HTTPException(status_code=400, detail="内置智能体不可删除")
|
|
db.delete(a)
|
|
db.commit()
|
|
return ok(message="已删除")
|