session_service.py
13.9 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
from __future__ import annotations
import json
import secrets
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.session_store import SESSION_TTL_SECONDS, SessionStore
from app.model.agent import Agent
from app.model.session import ConversationHistory, Session as DbSession, SessionStatus
from app.schema.session import (
SessionArchiveResponse,
SessionContextResponse,
SessionCreateRequest,
SessionCreateResponse,
SessionDetailResponse,
SessionHistoryTurn,
SessionInfo,
SessionUpdateRequest,
SessionUpdateResponse,
)
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
def _gen_session_id() -> str:
return f"sess_{secrets.token_urlsafe(12)}"
def _merge_entities(base: dict[str, Any], incoming: Optional[dict[str, Any]]) -> dict[str, Any]:
if not incoming:
return base
merged = dict(base)
merged.update(incoming)
return merged
@dataclass(frozen=True)
class _ActiveSessionPayload:
session_id: str
user_id: str
channel: str
room_id: str = ""
current_agent_id: int = 101
current_agent_code: Optional[str] = None
conversation_history: list[dict[str, Any]] = field(default_factory=list)
context_entities: dict[str, Any] = field(default_factory=dict)
created_at: str = ""
updated_at: str = ""
class SessionService:
def __init__(self, db: OrmSession, store: Optional[SessionStore] = None) -> None:
self.db = db
self.store = store or SessionStore()
def _default_agent_id(self) -> int:
agent = self.db.query(Agent).filter(Agent.is_deleted == False).order_by(Agent.id.asc()).first()
return agent.id if agent else 101
def create(self, req: SessionCreateRequest) -> SessionCreateResponse:
session_id = _gen_session_id()
now = _utcnow()
current_agent_id = self._default_agent_id()
payload = _ActiveSessionPayload(
session_id=session_id,
user_id=req.user_id,
channel=req.channel,
room_id="",
current_agent_id=current_agent_id,
current_agent_code=None,
conversation_history=[],
context_entities={},
created_at=now.isoformat(),
updated_at=now.isoformat(),
)
self.store.set(session_id, payload.__dict__)
return SessionCreateResponse(
session_id=session_id,
user_id=req.user_id,
channel=req.channel,
current_agent_id=current_agent_id,
created_at=now,
)
def append_and_merge(self, session_id: str, req: SessionUpdateRequest) -> SessionUpdateResponse:
existing = self.store.get(session_id)
if not existing:
raise ValueError("会话不存在或已超时")
now = _utcnow()
history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
history.append(
{
"role": req.role,
"content": req.content,
"agent_id": req.agent_id,
"intent": req.intent,
"timestamp": now.isoformat(),
}
)
entities = _merge_entities(existing.get("context_entities") or {}, req.entities or {})
existing["conversation_history"] = history
existing["context_entities"] = entities
existing["current_agent_id"] = req.agent_id
existing["updated_at"] = now.isoformat()
self.store.set(session_id, existing)
return SessionUpdateResponse(success=True, updated_at=now, turn_count=len(history))
def get_detail(self, session_id: str) -> SessionDetailResponse:
existing = self.store.get(session_id)
if existing:
agent_name = None
agent = self.db.query(Agent).filter(Agent.id == existing.get("current_agent_id")).first()
if agent:
agent_name = agent.name
history_items = []
for item in existing.get("conversation_history") or []:
history_items.append(
SessionHistoryTurn(
role=item["role"],
content=item["content"],
agent_id=item.get("agent_id"),
intent=item.get("intent"),
timestamp=datetime.fromisoformat(item["timestamp"]),
)
)
return SessionDetailResponse(
session_id=existing["session_id"],
user_id=existing["user_id"],
channel=existing["channel"],
current_agent_id=existing["current_agent_id"],
current_agent_name=agent_name,
conversation_history=history_items,
context_entities=existing.get("context_entities") or {},
created_at=datetime.fromisoformat(existing["created_at"]),
updated_at=datetime.fromisoformat(existing["updated_at"]),
)
db_sess = self.db.query(DbSession).filter(DbSession.session_id == session_id).first()
if not db_sess:
raise ValueError("会话不存在")
history_rows = (
self.db.query(ConversationHistory)
.filter(ConversationHistory.session_id == session_id)
.order_by(ConversationHistory.id.asc())
.all()
)
history_items = []
for row in history_rows:
history_items.append(
SessionHistoryTurn(
role=row.role,
content=row.content,
agent_id=row.agent_id,
intent=row.intent,
timestamp=row.timestamp.replace(tzinfo=timezone.utc) if row.timestamp.tzinfo is None else row.timestamp,
)
)
agent_name = None
agent = self.db.query(Agent).filter(Agent.id == db_sess.current_agent_id).first()
if agent:
agent_name = agent.name
# Archived sessions do not keep transient context_entities.
return SessionDetailResponse(
session_id=db_sess.session_id,
user_id=db_sess.user_id,
channel=db_sess.channel,
current_agent_id=db_sess.current_agent_id,
current_agent_name=agent_name,
conversation_history=history_items,
context_entities={},
created_at=db_sess.created_at.replace(tzinfo=timezone.utc) if db_sess.created_at.tzinfo is None else db_sess.created_at,
updated_at=db_sess.updated_at.replace(tzinfo=timezone.utc) if db_sess.updated_at.tzinfo is None else db_sess.updated_at,
)
def get_context(self, session_id: str) -> SessionContextResponse:
existing = self.store.get(session_id)
if not existing:
return SessionContextResponse(
session_id=session_id,
current_agent_id=0,
last_entities={},
inheritance_valid=False,
expires_at=None,
)
updated_at = datetime.fromisoformat(existing["updated_at"])
expires_at = updated_at + timedelta(seconds=SESSION_TTL_SECONDS)
return SessionContextResponse(
session_id=session_id,
current_agent_id=existing["current_agent_id"],
last_entities=existing.get("context_entities") or {},
inheritance_valid=True,
expires_at=expires_at,
)
def archive(self, session_id: str) -> SessionArchiveResponse:
existing = self.store.get(session_id)
if not existing:
raise ValueError("会话不存在或已超时")
now = _utcnow()
db_sess = self.db.query(DbSession).filter(DbSession.session_id == session_id).first()
if not db_sess:
db_sess = DbSession(
session_id=session_id,
user_id=existing["user_id"],
channel=existing["channel"],
current_agent_id=existing["current_agent_id"],
status=SessionStatus.archived.value,
)
self.db.add(db_sess)
else:
db_sess.status = SessionStatus.archived.value
db_sess.current_agent_id = existing["current_agent_id"]
for item in existing.get("conversation_history") or []:
self.db.add(
ConversationHistory(
session_id=session_id,
role=item["role"],
content=item["content"],
agent_id=item.get("agent_id"),
intent=item.get("intent"),
entities_json=json.dumps(existing.get("context_entities") or {}, ensure_ascii=False),
)
)
self.db.commit()
self.store.delete(session_id)
return SessionArchiveResponse(success=True, archived_at=now)
# ── AgentHub 内部 API ──────────────────────────────────────────────
def get_or_create_session(
self,
session_id: str,
room_id: str = "",
user_id: str = "",
channel: str = "wechat_group",
) -> SessionInfo:
"""获取或创建活跃会话。session_id 为空时自动生成。先查 KV store,再查 DB。"""
from app.schema.session import SessionInfo
if not session_id:
session_id = _gen_session_id()
existing = self.store.get(session_id)
if existing:
return SessionInfo(
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"),
status="active",
)
now = _utcnow()
current_agent_id = self._default_agent_id()
payload = {
"session_id": session_id,
"user_id": user_id,
"channel": channel,
"room_id": room_id,
"current_agent_id": current_agent_id,
"current_agent_code": None,
"conversation_history": [],
"context_entities": {},
"created_at": now.isoformat(),
"updated_at": now.isoformat(),
}
self.store.set(session_id, payload)
return SessionInfo(
id=session_id,
session_id=session_id,
user_id=user_id,
channel=channel,
room_id=room_id,
current_agent_code=None,
status="active",
)
def add_message(
self,
session_id: str,
role: str,
content: str,
agent_code: Optional[str] = None,
) -> None:
"""向活跃会话的 conversation_history 追加一条消息。session_id 是字符串(如 sess_xxx)。"""
existing = self.store.get(session_id)
if not existing:
return
history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
history.append({
"role": role,
"content": content,
"agent_code": agent_code,
"agent_id": None,
"intent": None,
"timestamp": _utcnow().isoformat(),
})
existing["conversation_history"] = history
existing["updated_at"] = _utcnow().isoformat()
self.store.set(session_id, existing)
def get_session_messages(self, session_id: str) -> list[dict[str, Any]]:
"""返回 conversation_history 原始 dict 列表。AgentHub 自行决定取最近 N 条。"""
existing = self.store.get(session_id)
if not existing:
return []
return list(existing.get("conversation_history") or [])
def update_current_agent(self, session_id: str, agent_code: str) -> None:
"""更新活跃会话的 current_agent_code,用于继承路由。"""
existing = self.store.get(session_id)
if not existing:
return
existing["current_agent_code"] = agent_code
existing["updated_at"] = _utcnow().isoformat()
self.store.set(session_id, existing)
def get_session(self, session_id: str) -> Optional[SessionInfo]:
"""按 session_id 获取单个会话(仅 KV store 活跃会话)。"""
from app.schema.session import SessionInfo
existing = self.store.get(session_id)
if not existing:
return None
return SessionInfo(
id=session_id,
session_id=session_id,
user_id=existing.get("user_id", ""),
channel=existing.get("channel", ""),
room_id=existing.get("room_id", ""),
current_agent_code=existing.get("current_agent_code"),
status="active",
)
def get_session_by_uuid(self, session_id: str) -> Optional[SessionInfo]:
"""按 UUID 获取会话(= get_session 的别名,语义一致)。"""
return self.get_session(session_id)
def ensure_active_session(self, session_id: str, user_id: str, channel: str, room_id: str = "") -> None:
"""Ensure session exists in KV store (create if not found, refresh TTL if exists)."""
existing = self.store.get(session_id)
if existing:
self.store.refresh_ttl(session_id)
return
now = _utcnow()
current_agent_id = self._default_agent_id()
payload = {
"session_id": session_id,
"user_id": user_id,
"channel": channel,
"room_id": room_id,
"current_agent_id": current_agent_id,
"current_agent_code": None,
"conversation_history": [],
"context_entities": {},
"created_at": now.isoformat(),
"updated_at": now.isoformat(),
}
self.store.set(session_id, payload)