Files
ecom-dmb/apps/agent/application/session_service.py
T

76 lines
2.6 KiB
Python

"""会话用例。"""
from __future__ import annotations
import uuid
from datetime import datetime
from application.llm_settings_service import LlmRuntimeService
from domain.models import Actor, Session, SessionStatus
from domain.ports import SessionRepository
class SessionService:
def __init__(
self,
sessions: SessionRepository,
llm_runtime: LlmRuntimeService | None = None,
) -> None:
self._sessions = sessions
self._llm_runtime = llm_runtime
async def create(
self,
actor: Actor,
title: str | None = None,
llm_model: str | None = None,
) -> Session:
now = datetime.utcnow()
model = (llm_model or "").strip() or None
if not model and self._llm_runtime is not None:
try:
rt = await self._llm_runtime.resolve_runtime(actor.company_id)
model = rt.model or None
except Exception:
model = None
session = Session(
thread_id=str(uuid.uuid4()),
company_id=actor.company_id,
user_id=actor.user_id,
title=(title or "新对话").strip() or "新对话",
status=SessionStatus.ACTIVE,
llm_model=model,
created_at=now,
updated_at=now,
)
return await self._sessions.create(session)
async def list_mine(self, actor: Actor) -> list[Session]:
return await self._sessions.list_active(actor.company_id, actor.user_id)
async def require_owned(self, actor: Actor, thread_id: str) -> Session:
session = await self._sessions.get(actor.company_id, actor.user_id, thread_id)
if session is None or session.status == SessionStatus.DELETED:
raise LookupError("会话不存在")
return session
async def rename(self, actor: Actor, thread_id: str, title: str) -> Session:
session = await self.require_owned(actor, thread_id)
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def update_llm_model(
self, actor: Actor, thread_id: str, llm_model: str
) -> Session:
model = (llm_model or "").strip()
if not model:
raise ValueError("模型不能为空")
session = await self.require_owned(actor, thread_id)
session.llm_model = model
return await self._sessions.update(session)
async def archive(self, actor: Actor, thread_id: str) -> Session:
session = await self.require_owned(actor, thread_id)
session.status = SessionStatus.ARCHIVED
return await self._sessions.update(session)