feat(sprint6a): блок A — structured output, intent_steps, sticky-удержание

Заменили строковый тег [STATE: ...] из Спринта 5 на структурированный выход
ветки в виде JSON-блока в хвосте ответа: {state_after, slots_updated}, парсимый
балансировкой скобок. Шаги state machine вынесены из монолитного промпта в
таблицу intent_steps (intent_id FK, code, name, order_index, system_prompt,
allowed_next JSON, guards JSON) и редактируются через UI. Валидатор переходов
сверяет state_after с allowed_next и блокирует невалидные прыжки.

Базовый промпт new_booking разбит на base + 6 файлов шагов (intro/qualify/
present/offer_time/book/close), которые сидятся при старте через
ensure_seed_steps. В chat_service промпт собирается как base + step + блок
[ТЕКУЩЕЕ СОСТОЯНИЕ].

Попутно реализован мини-блок G (sticky state machine): когда диалог идёт по
sm-ветке и роутер на новой реплике предлагает другую — state НЕ сбрасывается,
в системный промпт ветки подаётся блок [ПОДСКАЗКА РОУТЕРА], LLM сама решает
(STATE_JSON или INTENT_CHANGE). Это сняло ключевую дыру Спринта 5: «Меня
зовут Алексей» / «болит ухо» внутри записи больше не сбрасывают сценарий.

Промпт ветки new_booking ужесточён: бытовые жалобы — это повод записи (слот
reason + сочувствие), не повод уводить в medical_question. Шаг present теперь
использует reason в формулировке. Промпт _router расширен живыми примерами
для всех 6 веток, особенно для reschedule («не смогу подойти», «перенесите»).

Надёжность внешнего LLM:
- ретрай в LLMClient с паузой 500 мс + новое исключение LLMUnavailableError;
- ретрай в RouterClient (DeepSeek периодически моргает);
- /chat при ошибке делает session.rollback() и возвращает 503 с понятным
  сообщением — больше не остаётся «диалогов-призраков» с одной репликой;
- UI убирает свой пузырь и возвращает текст в поле ввода для повторной отправки.

UI «Настройки» — добавлена вкладка «Шаги» для веток с state machine: список
шагов chip-ами, редактор промпта/имени/allowed_next/guards, сохранение через
PATCH /intents/{code}/steps/{step_code} без версионирования. Иконка ⓘ возле
поля «Правила» открывает popover с пояснением, что туда писать.

UI «Песочница»:
- блок «Состояние диалога» показывает имя шага из intent_steps (а не сырое
  число), для не-sm-веток пишется «без пошагового сценария»;
- подсветка illegal-переходов (валидатор отклонил state_after) и parse_error
  для sm-веток;
- блок «Решение роутера» развёрнут в три исхода: «попал в ту же ветку» /
  «удержались в ветке» / «ветка сама передала управление через INTENT_CHANGE»;
- секция «Найденные фрагменты» сворачивается, карточки чанков раскрываются
  по клику — правый сайдбар стал компактнее.

Терминология (по договорённости — простой русский в UI):
- «тред» → «диалог» в текстах для оператора (в коде/API thread_id оставлен);
- «sticky state machine» → «удержались в ветке»;
- «state machine» → «пошаговый сценарий» в видимых местах.

SPRINTS.md: блок G в Спринте 6b сокращён — sticky-логика уже сделана здесь,
осталась только вторая линия (передача thread_state в системный промпт самого
роутера для ещё более точной первичной классификации).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
AR 15 M4
2026-04-25 11:45:42 +05:00
parent 248cb37f8a
commit 9eef2dab3a
28 changed files with 1469 additions and 264 deletions
+60 -4
View File
@@ -3,11 +3,16 @@ import logging
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from db.models import Intent
from db.models import Intent, IntentStep
from db.session import get_session
from models.requests import IntentToggleRequest
from models.responses import IntentInfo, IntentListResponse
from services import config_service, intent_service
from models.requests import IntentStepUpdateRequest, IntentToggleRequest
from models.responses import (
IntentInfo,
IntentListResponse,
IntentStepInfo,
IntentStepListResponse,
)
from services import config_service, intent_service, intent_step_service
logger = logging.getLogger(__name__)
@@ -53,3 +58,54 @@ async def toggle_intent(
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),
)
@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)