"""对话用例:落库 + 记忆注入 + MCP tools + 流式生成。""" from __future__ import annotations from datetime import datetime from typing import AsyncIterator from application.llm_settings_service import LlmRuntimeService from application.memory_service import MemoryService from application.session_service import SessionService from config.settings import Settings from domain.models import Actor, ChatMessage, MessageRole from domain.ports import ChatStreamer, MessageRepository, SessionRepository from infrastructure.builtin_tools import builtin_tools from infrastructure.mcp_client import load_mcp_tools class ChatService: def __init__( self, settings: Settings, sessions: SessionService, session_repo: SessionRepository, messages: MessageRepository, llm_runtime: LlmRuntimeService, memory: MemoryService, streamer: ChatStreamer, ) -> None: self._settings = settings self._sessions = sessions self._session_repo = session_repo self._messages = messages self._llm_runtime = llm_runtime self._memory = memory self._streamer = streamer async def list_messages(self, actor: Actor, thread_id: str) -> list[ChatMessage]: await self._sessions.require_owned(actor, thread_id) return await self._messages.list_recent( actor.company_id, actor.user_id, thread_id, self._settings.chat_history_limit, ) async def stream_chat( self, actor: Actor, thread_id: str, content: str ) -> AsyncIterator[str]: text = (content or "").strip() if not text: raise ValueError("消息不能为空") session = await self._sessions.require_owned(actor, thread_id) llm = await self._llm_runtime.resolve_runtime(actor.company_id) await self._memory.maybe_capture_from_user( actor, thread_id=thread_id, text=text ) memory_lines = await self._memory.lines_for_prompt(actor) mcp_tools = await load_mcp_tools( self._settings, company_id=actor.company_id, user_id=actor.user_id ) # 本地时间工具始终挂上,不依赖 MCP 是否可用 tools = [*builtin_tools(), *mcp_tools] history = await self._messages.list_recent( actor.company_id, actor.user_id, thread_id, self._settings.chat_history_limit, ) seq = await self._messages.next_seq(actor.company_id, actor.user_id, thread_id) user_msg = ChatMessage( company_id=actor.company_id, user_id=actor.user_id, thread_id=thread_id, seq=seq, role=MessageRole.USER, content=text, ) await self._messages.append(user_msg) if session.title == "新对话": session.title = text[:40] + ("…" if len(text) > 40 else "") session.last_message_at = datetime.utcnow() await self._session_repo.update(session) parts: list[str] = [] async for chunk in self._streamer.stream_reply( llm=llm, history=history, user_text=text, memory_lines=memory_lines, tools=tools or None, ): parts.append(chunk) yield chunk full = "".join(parts).strip() or "(模型未返回内容)" a_seq = await self._messages.next_seq(actor.company_id, actor.user_id, thread_id) await self._messages.append( ChatMessage( company_id=actor.company_id, user_id=actor.user_id, thread_id=thread_id, seq=a_seq, role=MessageRole.ASSISTANT, content=full, ) ) session.last_message_at = datetime.utcnow() await self._session_repo.update(session)