Files
RAG_helper/services/thread_state_service.py
T
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

128 lines
4.4 KiB
Python

"""State machine треда: текущая ветка, шаг внутри ветки, собранные слоты.
Используется в chat_service для ведения многошаговых сценариев (Спринт 5).
Слоты — произвольный JSON-словарь, конкретные ключи определяются веткой.
"""
import json
import logging
from datetime import datetime, timezone
from sqlalchemy.ext.asyncio import AsyncSession
from db.models import ThreadState
logger = logging.getLogger(__name__)
async def get_state(session: AsyncSession, thread_id: int) -> ThreadState | None:
return await session.get(ThreadState, thread_id)
def _parse_slots(raw: str) -> dict:
if not raw:
return {}
try:
value = json.loads(raw)
except json.JSONDecodeError:
logger.warning("Bad slots_json for thread_state, resetting to {}")
return {}
return value if isinstance(value, dict) else {}
async def load_snapshot(session: AsyncSession, thread_id: int) -> dict:
"""Снимок состояния диалога: текущая ветка/шаг/слоты + handoff_count + suspended_*."""
state = await get_state(session, thread_id)
if state is None:
return {
"current_intent_code": None,
"current_step": 0,
"current_step_code": None,
"slots": {},
"handoff_count": 0,
"suspended_intent": None,
"resumable_step_code": None,
"resumable_slots": {},
}
resumable_slots = {}
if state.resumable_slots_json:
try:
value = json.loads(state.resumable_slots_json)
if isinstance(value, dict):
resumable_slots = value
except json.JSONDecodeError:
logger.warning("Bad resumable_slots_json for thread_state, ignoring")
return {
"current_intent_code": state.current_intent_code,
"current_step": state.current_step,
"current_step_code": state.current_step_code,
"slots": _parse_slots(state.slots_json),
"handoff_count": state.handoff_count,
"suspended_intent": state.suspended_intent,
"resumable_step_code": state.resumable_step_code,
"resumable_slots": resumable_slots,
}
async def upsert(
session: AsyncSession,
thread_id: int,
*,
intent_code: str | None,
step: int,
slots: dict,
step_code: str | None = None,
handoff_count: int = 0,
suspended_intent: str | None = None,
resumable_step_code: str | None = None,
resumable_slots: dict | None = None,
) -> ThreadState:
"""Создать или обновить состояние треда. Коммит — на совести вызывающего."""
state = await get_state(session, thread_id)
now = datetime.now(timezone.utc)
slots_raw = json.dumps(slots or {}, ensure_ascii=False)
resumable_raw = (
json.dumps(resumable_slots, ensure_ascii=False)
if resumable_slots is not None and len(resumable_slots) > 0
else None
)
if state is None:
state = ThreadState(
thread_id=thread_id,
current_intent_code=intent_code,
current_step=step,
current_step_code=step_code,
slots_json=slots_raw,
handoff_count=handoff_count,
suspended_intent=suspended_intent,
resumable_step_code=resumable_step_code,
resumable_slots_json=resumable_raw,
updated_at=now,
)
session.add(state)
else:
state.current_intent_code = intent_code
state.current_step = step
state.current_step_code = step_code
state.slots_json = slots_raw
state.handoff_count = handoff_count
state.suspended_intent = suspended_intent
state.resumable_step_code = resumable_step_code
state.resumable_slots_json = resumable_raw
state.updated_at = now
return state
async def reset(
session: AsyncSession,
thread_id: int,
*,
new_intent_code: str | None,
new_step_code: str | None = None,
) -> ThreadState:
"""Сбросить шаг и слоты треда, выставить новую ветку (при смене intent)."""
return await upsert(
session, thread_id,
intent_code=new_intent_code, step=0, step_code=new_step_code, slots={},
handoff_count=0,
)