feat: 新增agent

This commit is contained in:
2026-09-18 17:34:38 +08:00
parent 0d9b5a21c2
commit bc73668737
64 changed files with 3293 additions and 18 deletions
View File
+109
View File
@@ -0,0 +1,109 @@
"""对话用例:落库 + 记忆注入 + 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.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)
tools = await load_mcp_tools(
self._settings, company_id=actor.company_id, user_id=actor.user_id
)
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)
@@ -0,0 +1,48 @@
"""租户 LLM 运行时解析:Redis(Server 写入)→ Server 内部 API → 本地 fallback。"""
from __future__ import annotations
from fastapi import HTTPException, status
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeCache, LlmRuntimeGateway
class LlmRuntimeService:
def __init__(
self,
settings: Settings,
cache: LlmRuntimeCache,
gateway: LlmRuntimeGateway,
) -> None:
self._settings = settings
self._cache = cache
self._gateway = gateway
async def resolve_runtime(self, company_id: int) -> LlmRuntimeConfig:
cached = await self._cache.get(company_id)
if cached is not None and cached.api_key:
return cached
remote = await self._gateway.fetch(company_id)
if remote is not None and remote.api_key and remote.base_url and remote.model:
await self._cache.set(
company_id, remote, self._settings.llm_cache_ttl_seconds
)
return remote
if (
self._settings.llm_fallback_enabled
and self._settings.llm_fallback_api_key
):
return LlmRuntimeConfig(
base_url=self._settings.llm_fallback_base_url.rstrip("/"),
api_key=self._settings.llm_fallback_api_key,
model=self._settings.llm_fallback_model,
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="当前公司尚未配置模型 API,请先在智能助手设置中填写 OpenAI Compatible 凭证",
)
+66
View File
@@ -0,0 +1,66 @@
"""用户记忆用例。"""
from __future__ import annotations
import hashlib
import re
from domain.models import Actor, MemoryKind, UserMemory
from domain.ports import MemoryRepository
from config.settings import Settings
_REMEMBER_RE = re.compile(
r"^(?:请?记住|记住一下)[::\s]*(.+)$",
re.DOTALL,
)
class MemoryService:
def __init__(self, settings: Settings, repo: MemoryRepository) -> None:
self._settings = settings
self._repo = repo
async def list_public(self, actor: Actor, limit: int = 50) -> list[dict]:
rows = await self._repo.list_active(actor.company_id, actor.user_id, limit)
return [
{
"id": m.id,
"kind": m.kind.value,
"key": m.key,
"text": m.text,
"updatedAt": m.updated_at.isoformat() + "Z",
}
for m in rows
]
async def delete(self, actor: Actor, memory_id: str) -> bool:
return await self._repo.soft_delete(actor.company_id, actor.user_id, memory_id)
async def lines_for_prompt(self, actor: Actor) -> list[str]:
rows = await self._repo.list_active(
actor.company_id, actor.user_id, self._settings.memory_inject_limit
)
return [m.text.strip() for m in rows if m.text and m.text.strip()]
async def maybe_capture_from_user(
self, actor: Actor, *, thread_id: str, text: str
) -> None:
"""显式「记住…」指令写入记忆;自动抽取留给 P2。"""
m = _REMEMBER_RE.match((text or "").strip())
if not m:
return
body = m.group(1).strip()
if not body:
return
key = "remember:" + hashlib.sha1(body.encode("utf-8")).hexdigest()[:16]
await self._repo.upsert(
UserMemory(
company_id=actor.company_id,
user_id=actor.user_id,
kind=MemoryKind.PREFERENCE,
key=key,
text=body[:1000],
source_thread_id=thread_id,
)
)
+46
View File
@@ -0,0 +1,46 @@
"""会话用例。"""
from __future__ import annotations
import uuid
from datetime import datetime
from domain.models import Actor, Session, SessionStatus
from domain.ports import SessionRepository
class SessionService:
def __init__(self, sessions: SessionRepository) -> None:
self._sessions = sessions
async def create(self, actor: Actor, title: str | None = None) -> Session:
now = datetime.utcnow()
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,
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 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)