Files
AR 15 M4 932b488bcb feat(sprint6a): блоки A2, B, C — exit_conditions, handoff_count, suspended/resume
Блок A2: вынос условий выхода из основного промпта в отдельное поле
agent_configs.exit_conditions_text. compose_full_system_prompt склеивает
system_prompt + rules_text + exit_conditions_text перед отправкой в модель.
Одноразовая миграция данных при старте: пытаемся выделить блок «Условия
выхода» из хвоста существующих system_prompt-ов и перенести в новое поле
(поддерживаются три формы заголовка: «## Условия выхода», «**Условия
выхода**», просто «Условия выхода:»). В UI «Настройки» — третья textarea
с подсказкой ⓘ на отдельной кнопке.

Блок B: защита от петель маршрутизации (v2 §4.3). В thread_state добавлена
колонка handoff_count, инкрементируется на каждом hard-handoff: либо когда
роутер переключает не-sm-ветку (state reset), либо когда sm-ветка сама
выдаёт [INTENT_CHANGE: …] (bouncing). При превышении HANDOFF_CAP=3 диалог
автоматически уводится в escalate_human с шаблонным ответом «Уточню детали
с администратором клиники, свяжемся с вами в течение ближайшего часа», LLM
не вызывается, handoff_count сбрасывается. В Песочнице видны счётчик
«переключений ветки в диалоге» и красная плашка при срабатывании защиты.
Также пофикшен баг: для не-sm-веток snapshot.current_intent_code теперь
финализируется на served_code, иначе на следующей реплике prev_intent_code
терялся и handoff_count не считался.

Блок C: suspended_intent / resumable_step_code / resumable_slots_json в
thread_state (v2 §4.4). При hard-handoff из sm-ветки через [INTENT_CHANGE]
текущий сценарий запоминается (если suspended ещё не занят). Когда роутер
на следующих репликах возвращает intent = suspended_intent — RESUME:
восстанавливаем current_intent_code, current_step_code, slots; suspended_*
очищается, handoff_count=0. Возврат имеет приоритет над sticky-логикой.
В Песочнице — синяя плашка «📌 отложен сценарий X (шаг Y)» во время detour'а
и зелёная «↩️ возврат к отложенному сценарию» в момент resume. Routing-loop
guard и роутер-driven handoff не теряют suspended (только при authoritative
сценариях вроде эскалации он сбрасывается).

Прогон вручную: detour из new_booking/qualify в price_question и обратно
восстанавливает name=Алексей, reason=болит ухо на исходном шаге.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 12:46:10 +05:00

129 lines
4.8 KiB
Python

import logging
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from db.models import AgentConfig
from db.session import get_session
from models.requests import AgentConfigCreateRequest
from models.responses import (
AgentConfigDeleteResponse,
AgentConfigInfo,
AgentConfigListResponse,
)
from services import config_service, intent_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/configs", tags=["configs"])
def _to_info(cfg: AgentConfig, intent_code: str = "", intent_name: str = "") -> AgentConfigInfo:
return AgentConfigInfo(
id=cfg.id,
intent_id=cfg.intent_id,
intent_code=intent_code,
intent_name=intent_name,
version=cfg.version,
name=cfg.name,
system_prompt=cfg.system_prompt,
rules_text=cfg.rules_text or "",
exit_conditions_text=cfg.exit_conditions_text or "",
is_active=cfg.is_active,
created_at=cfg.created_at.isoformat(),
)
async def _resolve_intent_meta(session: AsyncSession, intent_id: int | None) -> tuple[str, str]:
if intent_id is None:
return "", ""
from db.models import Intent
intent = await session.get(Intent, intent_id)
if intent is None:
return "", ""
return intent.code, intent.name
@router.get("", response_model=AgentConfigListResponse)
async def list_configs(
intent_code: str = Query(..., description="Код ветки (обязателен): фильтр версий по ветке"),
session: AsyncSession = Depends(get_session),
):
intent = await intent_service.get_intent_by_code(session, intent_code)
if intent is None:
raise HTTPException(status_code=404, detail=f"Intent {intent_code!r} not found")
configs = await config_service.list_configs_for_intent(session, intent.id)
return AgentConfigListResponse(
configs=[_to_info(c, intent.code, intent.name) for c in configs],
total=len(configs),
)
@router.get("/active", response_model=AgentConfigInfo)
async def get_active(
intent_code: str = Query(..., description="Код ветки"),
session: AsyncSession = Depends(get_session),
):
intent = await intent_service.get_intent_by_code(session, intent_code)
if intent is None:
raise HTTPException(status_code=404, detail=f"Intent {intent_code!r} not found")
cfg = await config_service.get_active_config_for_intent(session, intent.id)
if cfg is None:
raise HTTPException(status_code=404, detail=f"No active config for intent {intent_code!r}")
return _to_info(cfg, intent.code, intent.name)
@router.get("/{config_id}", response_model=AgentConfigInfo)
async def get_config(config_id: int, session: AsyncSession = Depends(get_session)):
cfg = await config_service.get_config(session, config_id)
if cfg is None:
raise HTTPException(status_code=404, detail="Config not found")
code, name = await _resolve_intent_meta(session, cfg.intent_id)
return _to_info(cfg, code, name)
@router.post("", response_model=AgentConfigInfo)
async def create_config(
req: AgentConfigCreateRequest,
session: AsyncSession = Depends(get_session),
):
from db.models import Intent
intent = await session.get(Intent, req.intent_id)
if intent is None:
raise HTTPException(status_code=404, detail=f"Intent {req.intent_id} not found")
cfg = await config_service.create_config(
session=session,
intent_id=req.intent_id,
system_prompt=req.system_prompt,
rules_text=req.rules_text,
exit_conditions_text=req.exit_conditions_text,
name=req.name,
activate=req.activate,
)
return _to_info(cfg, intent.code, intent.name)
@router.post("/{config_id}/activate", response_model=AgentConfigInfo)
async def activate_config(config_id: int, session: AsyncSession = Depends(get_session)):
cfg = await config_service.activate_config(session, config_id)
if cfg is None:
raise HTTPException(status_code=404, detail="Config not found or has no intent")
code, name = await _resolve_intent_meta(session, cfg.intent_id)
return _to_info(cfg, code, name)
@router.delete("/{config_id}", response_model=AgentConfigDeleteResponse)
async def delete_config(config_id: int, session: AsyncSession = Depends(get_session)):
ok, reason = await config_service.delete_config(session, config_id)
if not ok:
if reason == "not_found":
raise HTTPException(status_code=404, detail="Config not found")
if reason == "active":
raise HTTPException(
status_code=400,
detail="Нельзя удалить активную версию — сначала активируйте другую",
)
return AgentConfigDeleteResponse(ok=True)