Files
ChatAIBot/routers/sessions.py
T
2026-05-29 08:52:33 +03:00

90 lines
2.9 KiB
Python

from fastapi import APIRouter, HTTPException
from services.memory import (
get_all_sessions,
get_or_create_session,
delete_session,
update_session_title,
update_session_persona,
get_history,
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,
get_session,
)
from models.schemas import ForkSessionRequest
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(session_id: str):
sessions = await get_all_sessions()
s = next((x for x in sessions if x["session_id"] == session_id), None)
if not s:
raise HTTPException(status_code=404, detail="Сессия не найдена")
return s
@router.patch("/{session_id}")
async def patch_session(session_id: str, data: dict):
await get_or_create_session(session_id, data.get("persona_id", "default"))
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}