Files
aiagent/backend/app/api/platform_templates.py
renjianbo 0608161c82 feat: 完善企业场景多线路由与执行稳定性
补齐平台模板与场景 DSL、预算控制、执行看板和企业场景脚本,增强 Windows 启动/迁移与前端代理和聊天会话记忆,修复执行创建阶段 500 与异步链路排障体验。

Made-with: Cursor
2026-04-09 21:58:53 +08:00

73 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
场景模板 API独立路由避免与 /api/v1/agents/{agent_id} 在部分部署中的匹配顺序问题)。
"""
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from typing import List
import logging
from app.core.database import get_db
from app.api.auth import get_current_user
from app.models.user import User
from app.models.agent import Agent
from app.core.exceptions import ValidationError, ConflictError
from app.services.workflow_validator import validate_workflow
from app.services.scene_templates import build_workflow_for_template, list_scene_template_meta
from app.api.agents import AgentResponse, SceneTemplateItem, AgentFromSceneTemplateCreate
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/platform", tags=["platform-templates"])
@router.get("/scene-templates", response_model=List[SceneTemplateItem])
async def list_scene_templates_v1(current_user: User = Depends(get_current_user)):
_ = current_user
return list_scene_template_meta()
@router.post("/agents/from-template", response_model=AgentResponse, status_code=status.HTTP_201_CREATED)
async def create_agent_from_template_v1(
body: AgentFromSceneTemplateCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
try:
workflow_config = build_workflow_for_template(
body.template_id, body.parameters or {}
)
except ValueError as e:
raise ValidationError(str(e))
validation_result = validate_workflow(
workflow_config.get("nodes", []), workflow_config.get("edges", [])
)
if not validation_result["valid"]:
raise ValidationError(
"工作流配置验证失败: " + ", ".join(validation_result["errors"])
)
existing_agent = db.query(Agent).filter(
Agent.name == body.name,
Agent.user_id == current_user.id,
).first()
if existing_agent:
raise ConflictError(f"Agent名称 '{body.name}' 已存在")
desc = body.description or f"自场景模板 {body.template_id} 创建"
agent = Agent(
name=body.name,
description=desc,
workflow_config=workflow_config,
budget_config=body.budget_config,
user_id=current_user.id,
status="draft",
)
db.add(agent)
db.commit()
db.refresh(agent)
logger.info(
f"用户 {current_user.username} 从模板 {body.template_id} 创建 Agent: {agent.name} ({agent.id})"
)
return agent