Files
RAG_helper/routers/chat.py
T
AR 15 M4 cac3d29273 feat(sprint5): state machine + bouncing — thread_state и служебные теги
Таблица thread_state (intent, step, slots) ведётся per-thread. В системный
промпт ветки дописывается текущее состояние, LLM возвращает служебный тег
[STATE: step=N; slots={...}] после основного ответа — парсер в chat_service
вырезает его и обновляет состояние. Если ветка решила, что тема ушла в другую,
она выдаёт [INTENT_CHANGE: code] — делаем один повторный вызов LLM с новой
веткой и сброшенным state (bouncing, MAX_BOUNCES=1). Если роутер сам выбрал
другую ветку, чем в thread_state, — state тоже сбрасывается. Промпт new_booking
переписан под 6-шаговый сценарий (имя → повод → специалист → время → подтверждение
→ запись), в «Песочнице» появился блок «Состояние треда» с intent/step/slots
и списком переходов.

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

57 lines
2.1 KiB
Python

import logging
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from db.session import get_session
from models.requests import ChatRequest
from models.responses import BounceInfo, ChatResponse, SourceInfo, ThreadStateInfo
from services import chat_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/chat", tags=["chat"])
@router.post("", response_model=ChatResponse)
async def chat(req: ChatRequest, session: AsyncSession = Depends(get_session)):
from main import llm_client, router_client, vectorstore_service
if vectorstore_service is None or llm_client is None or router_client is None:
raise HTTPException(status_code=503, detail="Service not ready")
try:
result = await chat_service.send_message(
session=session,
vectorstore=vectorstore_service,
llm=llm_client,
router=router_client,
text=req.text,
thread_id=req.thread_id,
top_k=req.top_k,
temperature=req.temperature,
max_tokens=req.max_tokens,
)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.exception("Chat failed")
raise HTTPException(status_code=500, detail=f"Chat error [{type(e).__name__}]: {e}")
return ChatResponse(
thread_id=result["thread_id"],
thread_name=result["thread_name"],
message_id=result["message_id"],
intent_code=result["intent_code"],
intent_name=result["intent_name"],
router_intent_code=result.get("router_intent_code", ""),
config_version=result["config_version"],
router_version=result.get("router_version"),
answer=result["answer"],
sources=[SourceInfo(**s) for s in result["sources"]],
model_used=result["model_used"],
assembled_prompt=result["assembled_prompt"],
thread_state=ThreadStateInfo(**result["thread_state"]),
bounces=[BounceInfo(**b) for b in result.get("bounces", [])],
)