Files
ChatAIBot/routers/sessions.py
T
2026-06-02 15:03:39 +03:00

120 lines
4.1 KiB
Python

from fastapi import APIRouter, HTTPException
from services.memory import (
get_all_sessions,
get_session,
get_or_create_session,
get_history,
delete_session,
update_session_title,
update_session_persona,
get_message_count,
update_session_rpg,
update_session_facts,
update_session_global_plot,
update_session_status_quo,
update_session_genre,
update_session_rpg_settings,
get_quests,
get_last_message_preview,
fork_session,
)
from models.schemas import ForkSessionRequest, RebindPersonaRequest
from services.chat_prompt import get_system_prompt
from services.memory import rebind_session_persona
from services.personas import get_persona
router = APIRouter(prefix="/sessions", tags=["sessions"])
@router.get("/")
async def list_sessions():
sessions = await get_all_sessions()
result = []
for s in sessions:
count = await get_message_count(s["session_id"])
preview = await get_last_message_preview(s["session_id"])
result.append({**s, "message_count": count, "last_message_preview": preview})
return result
@router.get("/{session_id}/quests")
async def list_quests(session_id: str):
return await get_quests(session_id)
@router.get("/{session_id}")
async def get_session_route(session_id: str):
s = await get_session(session_id)
if not s:
raise HTTPException(status_code=404, detail="Сессия не найдена")
return s
@router.post("/{session_id}/rebind-persona")
async def rebind_persona(session_id: str, body: RebindPersonaRequest):
session = await get_session(session_id)
if not session:
raise HTTPException(status_code=404, detail="Сессия не найдена")
persona = await get_persona(body.persona_id)
if not persona:
raise HTTPException(status_code=400, detail="Персонаж не найден")
hist = [] if body.clear_history else await get_history(session_id)
static = await get_system_prompt(body.persona_id, hist, "")
first_mes = (persona.get("first_mes") or "").strip() if body.clear_history else None
try:
await rebind_session_persona(
session_id,
body.persona_id,
clear_history=body.clear_history,
static_prompt=static,
first_mes=first_mes or None,
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
return {
"persona_id": body.persona_id,
"persona_name": persona.get("name", body.persona_id),
"system_prompt_preview": static[:500],
"clear_history": body.clear_history,
}
@router.patch("/{session_id}")
async def patch_session(session_id: str, data: dict):
create_pid = data.get("persona_id") if "persona_id" in data else None
await get_or_create_session(session_id, create_pid)
if "title" in data:
await update_session_title(session_id, data["title"])
if "persona_id" in data:
await update_session_persona(session_id, data["persona_id"])
if "rpg_enabled" in data:
await update_session_rpg(session_id, bool(data["rpg_enabled"]))
if "facts_json" in data:
await update_session_facts(session_id, data["facts_json"])
if "global_plot" in data:
await update_session_global_plot(session_id, data["global_plot"])
if "status_quo" in data:
await update_session_status_quo(session_id, data["status_quo"])
if "genre" in data:
await update_session_genre(session_id, data["genre"])
if "rpg_settings_json" in data:
await update_session_rpg_settings(session_id, data["rpg_settings_json"])
return {"status": "updated"}
@router.post("/{session_id}/fork")
async def fork_session_route(session_id: str, req: ForkSessionRequest):
new_id = await fork_session(session_id, req.until_message_id)
if not new_id:
raise HTTPException(status_code=404, detail="Сессия не найдена")
return {"session_id": new_id, "source_session_id": session_id}
@router.delete("/{session_id}")
async def remove_session(session_id: str):
await delete_session(session_id)
return {"status": "deleted", "session_id": session_id}