a79b6f9d05
Хранить старый 6-шаговый сценарий new_booking параллельно с новым 4-шаговым,
чтобы оператор мог откатиться или сравнить варианты. Активный граф ровно один,
переключение через UI «Настройки → Шаги».
Модель и миграция:
- Таблица intent_step_graphs (id, intent_id, version, name, is_active, created_at).
- intent_steps.graph_id FK + UNIQUE сменён с (intent_id, code) на (graph_id, code).
- Alembic-миграция j6d8c4b56g23 (batch_alter_table для SQLite).
Сервис и сидинг (services/intent_step_graph_service.py):
- ensure_seed_graphs идемпотентен: создаёт активный граф для каждой ветки,
привязывает существующие шаги (graph_id IS NULL), для new_booking
восстанавливает архивный v1 из _archived_v1/*.md и _PRE_SPRINT_7_6_ALLOWED_NEXT.
- Активный граф new_booking сжат до 4 шагов: deprecated present/offer_time
удаляются из активного, остаются только в архивном v1.
- list_graphs / get_active_graph / set_active_graph.
API:
- GET /intents/{code}/step-graphs — список с steps_count и is_active.
- POST /intents/{code}/step-graphs/{graph_id}/activate.
- list_steps_for_intent / get_step_by_code / get_first_step фильтруют
по активному графу через _active_graph_filter (join с intent_step_graphs).
- ensure_seed_guards и migrate_new_booking_allowed_next_v2 защищены: не
трогают шаги архивных графов.
UI (static/settings.html):
- Во вкладке «Шаги» вверху блок «Версии графа шагов»: карточки с именем,
кол-вом шагов, бейджем «активная» или кнопкой «Активировать». При
переключении заголовок меняется «Шаги (4)» ↔ «Шаги (6)».
- Раздел «Тест-вопрос от пациента» сделан сворачиваемым (details/summary
в стиле prompt-block).
Промпты архивного графа восстановлены из коммита 60f8a7b^ в
prompts/intents/new_booking/steps/_archived_v1/*.md.
SPRINTS.md: Спринт 7.7 → ✅ Закрыт.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
195 lines
7.1 KiB
Python
195 lines
7.1 KiB
Python
import logging
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from db.models import Intent, IntentStep, IntentStepGraph
|
|
from db.session import get_session
|
|
from models.requests import (
|
|
IntentDocumentsUpdateRequest,
|
|
IntentStepUpdateRequest,
|
|
IntentToggleRequest,
|
|
)
|
|
from models.responses import (
|
|
IntentDocumentsResponse,
|
|
IntentInfo,
|
|
IntentListResponse,
|
|
IntentStepGraphInfo,
|
|
IntentStepGraphListResponse,
|
|
IntentStepInfo,
|
|
IntentStepListResponse,
|
|
)
|
|
from services import (
|
|
config_service,
|
|
intent_document_service,
|
|
intent_service,
|
|
intent_step_graph_service,
|
|
intent_step_service,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
router = APIRouter(prefix="/intents", tags=["intents"])
|
|
|
|
|
|
async def _to_info(session: AsyncSession, intent: Intent) -> IntentInfo:
|
|
active_cfg = await config_service.get_active_config_for_intent(session, intent.id)
|
|
return IntentInfo(
|
|
id=intent.id,
|
|
code=intent.code,
|
|
name=intent.name,
|
|
description=intent.description or "",
|
|
is_enabled=intent.is_enabled,
|
|
order_index=intent.order_index,
|
|
active_config_id=active_cfg.id if active_cfg else None,
|
|
active_config_version=active_cfg.version if active_cfg else None,
|
|
)
|
|
|
|
|
|
@router.get("", response_model=IntentListResponse)
|
|
async def list_intents(session: AsyncSession = Depends(get_session)):
|
|
intents = await intent_service.list_intents(session)
|
|
infos = [await _to_info(session, i) for i in intents]
|
|
return IntentListResponse(intents=infos, total=len(infos))
|
|
|
|
|
|
@router.get("/{code}", response_model=IntentInfo)
|
|
async def get_intent(code: str, session: AsyncSession = Depends(get_session)):
|
|
intent = await intent_service.get_intent_by_code(session, code)
|
|
if intent is None:
|
|
raise HTTPException(status_code=404, detail="Intent not found")
|
|
return await _to_info(session, intent)
|
|
|
|
|
|
@router.patch("/{code}", response_model=IntentInfo)
|
|
async def toggle_intent(
|
|
code: str,
|
|
req: IntentToggleRequest,
|
|
session: AsyncSession = Depends(get_session),
|
|
):
|
|
intent = await intent_service.set_intent_enabled(session, code, req.is_enabled)
|
|
if intent is None:
|
|
raise HTTPException(status_code=404, detail="Intent not found")
|
|
return await _to_info(session, intent)
|
|
|
|
|
|
def _step_to_info(step: IntentStep, intent_code: str) -> IntentStepInfo:
|
|
return IntentStepInfo(
|
|
id=step.id,
|
|
intent_id=step.intent_id,
|
|
intent_code=intent_code,
|
|
code=step.code,
|
|
name=step.name,
|
|
order_index=step.order_index,
|
|
system_prompt=step.system_prompt or "",
|
|
allowed_next=intent_step_service.parse_allowed_next(step),
|
|
guards=intent_step_service.parse_guards(step),
|
|
updated_at=step.updated_at.isoformat(),
|
|
)
|
|
|
|
|
|
@router.get("/{code}/steps", response_model=IntentStepListResponse)
|
|
async def list_intent_steps(code: str, session: AsyncSession = Depends(get_session)):
|
|
intent = await intent_service.get_intent_by_code(session, code)
|
|
if intent is None:
|
|
raise HTTPException(status_code=404, detail="Intent not found")
|
|
steps = await intent_step_service.list_steps_for_intent(session, intent.id)
|
|
return IntentStepListResponse(
|
|
intent_code=intent.code,
|
|
steps=[_step_to_info(s, intent.code) for s in steps],
|
|
total=len(steps),
|
|
)
|
|
|
|
|
|
def _graph_to_info(graph: IntentStepGraph, intent_code: str, steps_count: int) -> IntentStepGraphInfo:
|
|
return IntentStepGraphInfo(
|
|
id=graph.id,
|
|
intent_code=intent_code,
|
|
version=graph.version,
|
|
name=graph.name,
|
|
is_active=graph.is_active,
|
|
steps_count=steps_count,
|
|
created_at=graph.created_at.isoformat(),
|
|
)
|
|
|
|
|
|
@router.get("/{code}/step-graphs", response_model=IntentStepGraphListResponse)
|
|
async def list_intent_step_graphs(code: str, session: AsyncSession = Depends(get_session)):
|
|
intent = await intent_service.get_intent_by_code(session, code)
|
|
if intent is None:
|
|
raise HTTPException(status_code=404, detail="Intent not found")
|
|
pairs = await intent_step_graph_service.list_graphs(session, intent.id)
|
|
active_id = next((g.id for g, _ in pairs if g.is_active), None)
|
|
return IntentStepGraphListResponse(
|
|
intent_code=intent.code,
|
|
graphs=[_graph_to_info(g, intent.code, c) for g, c in pairs],
|
|
active_graph_id=active_id,
|
|
total=len(pairs),
|
|
)
|
|
|
|
|
|
@router.post("/{code}/step-graphs/{graph_id}/activate", response_model=IntentStepGraphListResponse)
|
|
async def activate_intent_step_graph(
|
|
code: str, graph_id: int, session: AsyncSession = Depends(get_session)
|
|
):
|
|
intent = await intent_service.get_intent_by_code(session, code)
|
|
if intent is None:
|
|
raise HTTPException(status_code=404, detail="Intent not found")
|
|
target = await intent_step_graph_service.set_active_graph(session, intent.id, graph_id)
|
|
if target is None:
|
|
raise HTTPException(status_code=404, detail="Step graph not found")
|
|
pairs = await intent_step_graph_service.list_graphs(session, intent.id)
|
|
return IntentStepGraphListResponse(
|
|
intent_code=intent.code,
|
|
graphs=[_graph_to_info(g, intent.code, c) for g, c in pairs],
|
|
active_graph_id=target.id,
|
|
total=len(pairs),
|
|
)
|
|
|
|
|
|
@router.patch("/{code}/steps/{step_code}", response_model=IntentStepInfo)
|
|
async def update_intent_step(
|
|
code: str,
|
|
step_code: str,
|
|
req: IntentStepUpdateRequest,
|
|
session: AsyncSession = Depends(get_session),
|
|
):
|
|
intent = await intent_service.get_intent_by_code(session, code)
|
|
if intent is None:
|
|
raise HTTPException(status_code=404, detail="Intent not found")
|
|
step = await intent_step_service.get_step_by_code(session, intent.id, step_code)
|
|
if step is None:
|
|
raise HTTPException(status_code=404, detail="Step not found")
|
|
updated = await intent_step_service.update_step(
|
|
session, step,
|
|
name=req.name,
|
|
system_prompt=req.system_prompt,
|
|
allowed_next=req.allowed_next,
|
|
guards=req.guards,
|
|
)
|
|
return _step_to_info(updated, intent.code)
|
|
|
|
|
|
@router.get("/{code}/documents", response_model=IntentDocumentsResponse)
|
|
async def list_intent_documents(code: str, session: AsyncSession = Depends(get_session)):
|
|
intent = await intent_service.get_intent_by_code(session, code)
|
|
if intent is None:
|
|
raise HTTPException(status_code=404, detail="Intent not found")
|
|
document_ids = await intent_document_service.list_documents_for_intent(session, intent.id)
|
|
return IntentDocumentsResponse(intent_code=intent.code, document_ids=document_ids)
|
|
|
|
|
|
@router.put("/{code}/documents", response_model=IntentDocumentsResponse)
|
|
async def set_intent_documents(
|
|
code: str,
|
|
req: IntentDocumentsUpdateRequest,
|
|
session: AsyncSession = Depends(get_session),
|
|
):
|
|
intent = await intent_service.get_intent_by_code(session, code)
|
|
if intent is None:
|
|
raise HTTPException(status_code=404, detail="Intent not found")
|
|
document_ids = await intent_document_service.set_documents_for_intent(
|
|
session, intent.id, req.document_ids,
|
|
)
|
|
return IntentDocumentsResponse(intent_code=intent.code, document_ids=document_ids)
|