active_session_service.py
2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional
from app.infrastructure.session_store import SessionStore
def _utcnow_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@dataclass(frozen=True)
class ActiveSessionInfo:
id: str
session_id: str
user_id: str
channel: str
room_id: str
current_agent_code: Optional[str]
status: str = "active"
class ActiveSessionService:
def __init__(self, store: Optional[SessionStore] = None) -> None:
self.store = store or SessionStore()
def get_or_create_session(
self,
session_id: str,
room_id: str = "",
user_id: str = "",
channel: str = "wechat_group",
) -> ActiveSessionInfo:
existing = self.store.get(session_id)
if existing:
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
user_id=existing.get("user_id", user_id),
channel=existing.get("channel", channel),
room_id=existing.get("room_id", room_id),
current_agent_code=existing.get("current_agent_code"),
)
payload = {
"session_id": session_id,
"user_id": user_id,
"channel": channel,
"room_id": room_id,
"current_agent_code": None,
"conversation_history": [],
"context_entities": {},
"created_at": _utcnow_iso(),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
user_id=user_id,
channel=channel,
room_id=room_id,
current_agent_code=None,
)
def update_current_agent(self, session_id: str, agent_code: str) -> None:
existing = self.store.get(session_id)
if not existing:
return
existing["current_agent_code"] = agent_code
existing["updated_at"] = _utcnow_iso()
self.store.set(session_id, existing)