- Replaced rigid TIERs with continuous COMPLEXITY 1-5 scale in semantics.md - Updated generate_semantic_map.py to parse and score based on Complexity - Added backward compatibility mapping for legacy TIERs - Migrated all .ai/shots examples to use @COMPLEXITY and updated relation syntax - Added trivial_utility.py shot to demonstrate implicit Complexity 1 token savings
75 lines
3.2 KiB
Python
75 lines
3.2 KiB
Python
#[DEF:BackendRouteShot:Module]
|
|
# @COMPLEXITY: 3
|
|
# @SEMANTICS: Route, Task, API, Async
|
|
# @PURPOSE: Reference implementation of a task-based route using GRACE-Poly.
|
|
# @LAYER: Interface (API)
|
|
# @RELATION: [IMPLEMENTS] ->[API_FastAPI]
|
|
|
|
from typing import Dict, Any
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from pydantic import BaseModel
|
|
# GRACE: Правильный импорт глобального логгера и scope
|
|
from ...core.logger import logger, belief_scope
|
|
from ...core.task_manager import TaskManager, Task
|
|
from ...core.config_manager import ConfigManager
|
|
from ...dependencies import get_task_manager, get_config_manager, get_current_user
|
|
|
|
router = APIRouter()
|
|
|
|
# [DEF:CreateTaskRequest:Class]
|
|
# @PURPOSE: DTO for task creation payload.
|
|
class CreateTaskRequest(BaseModel):
|
|
plugin_id: str
|
|
params: Dict[str, Any]
|
|
# [/DEF:CreateTaskRequest:Class]
|
|
|
|
# [DEF:create_task:Function]
|
|
# @COMPLEXITY: 4
|
|
# @PURPOSE: Create and start a new task using TaskManager. Non-blocking.
|
|
# @RELATION: [CALLS] ->[task_manager.create_task]
|
|
# @PRE: plugin_id must match a registered plugin.
|
|
# @POST: A new task is spawned; Task object returned immediately.
|
|
# @SIDE_EFFECT: Writes to DB, Triggers background worker.
|
|
# @DATA_CONTRACT: Input -> CreateTaskRequest, Output -> Task
|
|
@router.post("/tasks", response_model=Task, status_code=status.HTTP_201_CREATED)
|
|
async def create_task(
|
|
request: CreateTaskRequest,
|
|
task_manager: TaskManager = Depends(get_task_manager),
|
|
config: ConfigManager = Depends(get_config_manager),
|
|
current_user = Depends(get_current_user)
|
|
):
|
|
# GRACE: Открываем семантическую транзакцию
|
|
with belief_scope("create_task"):
|
|
try:
|
|
# GRACE: [REASON] - Фиксируем начало дедуктивной цепочки
|
|
logger.reason("Resolving configuration and spawning task", extra={"plugin_id": request.plugin_id})
|
|
|
|
timeout = config.get("TASKS_DEFAULT_TIMEOUT", 3600)
|
|
|
|
# @RELATION: CALLS -> task_manager.create_task
|
|
task = await task_manager.create_task(
|
|
plugin_id=request.plugin_id,
|
|
params={**request.params, "timeout": timeout}
|
|
)
|
|
|
|
# GRACE:[REFLECT] - Подтверждаем выполнение @POST перед выходом
|
|
logger.reflect("Task spawned successfully", extra={"task_id": task.id})
|
|
return task
|
|
|
|
except ValueError as e:
|
|
# GRACE: [EXPLORE] - Обработка ожидаемого отклонения
|
|
logger.explore("Domain validation error during task creation", exc_info=e)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=str(e)
|
|
)
|
|
except Exception as e:
|
|
# GRACE: [EXPLORE] - Обработка критического сбоя
|
|
logger.explore("Internal Task Spawning Error", exc_info=e)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Internal Task Spawning Error"
|
|
)
|
|
# [/DEF:create_task:Function]
|
|
|
|
# [/DEF:BackendRouteShot:Module] |