mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-25 06:29:20 +08:00
init
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
"""领域模型(无框架依赖)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
|
||||
class SessionStatus(str, Enum):
|
||||
ACTIVE = "active"
|
||||
ARCHIVED = "archived"
|
||||
DELETED = "deleted"
|
||||
|
||||
|
||||
class MessageRole(str, Enum):
|
||||
USER = "user"
|
||||
ASSISTANT = "assistant"
|
||||
SYSTEM = "system"
|
||||
TOOL = "tool"
|
||||
|
||||
|
||||
class MemoryKind(str, Enum):
|
||||
PREFERENCE = "preference"
|
||||
FACT = "fact"
|
||||
ENTITY = "entity"
|
||||
SUMMARY = "summary"
|
||||
|
||||
|
||||
class MemoryStatus(str, Enum):
|
||||
ACTIVE = "active"
|
||||
STALE = "stale"
|
||||
DELETED = "deleted"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Actor:
|
||||
"""当前请求主体。"""
|
||||
|
||||
user_id: str
|
||||
company_id: int
|
||||
company_role: str | None = None
|
||||
is_super: bool = False
|
||||
|
||||
def can_manage_llm(self) -> bool:
|
||||
if self.is_super:
|
||||
return True
|
||||
role = (self.company_role or "").lower()
|
||||
return role in {"owner", "admin"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class LlmResponseChain:
|
||||
"""同提供商同模型下的 Responses 续链缓存(非真相源;失效则 Mongo rebuild)。"""
|
||||
|
||||
provider_id: int | None
|
||||
model: str
|
||||
previous_response_id: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
thread_id: str
|
||||
company_id: int
|
||||
user_id: str
|
||||
title: str = "新对话"
|
||||
status: SessionStatus = SessionStatus.ACTIVE
|
||||
summary: str | None = None
|
||||
# general=经营助手;ecom_goods_publish=拼多多商品发布编辑
|
||||
scene: str = "general"
|
||||
# 场景业务键,如发布草稿 draftId
|
||||
scene_ref: str | None = None
|
||||
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
|
||||
llm_provider_id: int | None = None
|
||||
llm_model: str | None = None
|
||||
# Responses 续链;切换选型或链失效时清空
|
||||
llm_response_chain: LlmResponseChain | None = None
|
||||
created_at: datetime = field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = field(default_factory=datetime.utcnow)
|
||||
last_message_at: datetime | None = None
|
||||
|
||||
|
||||
SCENE_GENERAL = "general"
|
||||
SCENE_ECOM_GOODS_PUBLISH = "ecom_goods_publish"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatMessage:
|
||||
company_id: int
|
||||
user_id: str
|
||||
thread_id: str
|
||||
seq: int
|
||||
role: MessageRole
|
||||
content: str
|
||||
tool_name: str | None = None
|
||||
tool_call_id: str | None = None
|
||||
created_at: datetime = field(default_factory=datetime.utcnow)
|
||||
id: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class UserMemory:
|
||||
"""用户级长期记忆条目;summary 供检索,text 仅按需载入。"""
|
||||
|
||||
company_id: int
|
||||
user_id: str
|
||||
kind: MemoryKind
|
||||
text: str
|
||||
summary: str = ""
|
||||
key: str | None = None
|
||||
value: dict[str, Any] = field(default_factory=dict)
|
||||
source_thread_id: str | None = None
|
||||
status: MemoryStatus = MemoryStatus.ACTIVE
|
||||
confidence: float = 0.8
|
||||
created_at: datetime = field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = field(default_factory=datetime.utcnow)
|
||||
id: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LlmRuntimeConfig:
|
||||
"""注入 LLM 客户端的运行时配置(含明文 key,仅进程内)。"""
|
||||
|
||||
base_url: str
|
||||
api_key: str
|
||||
model: str
|
||||
provider_id: int | None = None
|
||||
extra_headers: dict[str, str] = field(default_factory=dict)
|
||||
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
|
||||
context_window: int | None = None
|
||||
# API 协议:auto | completions | responses
|
||||
api_style: str = "auto"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LlmProtocolCapability:
|
||||
"""按提供商缓存的协议能力;None 表示尚未验证。"""
|
||||
|
||||
responses: bool | None = None
|
||||
store: bool | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StreamEvent:
|
||||
"""流式片段:正文 token、服务端工具状态、或需前端执行的 client tool。"""
|
||||
|
||||
kind: str # token | tool | client_tool | pending_client_tools | response_chain
|
||||
text: str | None = None
|
||||
phase: str | None = None # start | end
|
||||
name: str | None = None
|
||||
label: str | None = None
|
||||
tool_call_id: str | None = None
|
||||
args: dict | None = None
|
||||
# Responses 本轮最终 response id(仅 kind=response_chain)
|
||||
response_id: str | None = None
|
||||
|
||||
@staticmethod
|
||||
def token(text: str) -> StreamEvent:
|
||||
return StreamEvent(kind="token", text=text)
|
||||
|
||||
@staticmethod
|
||||
def tool(*, phase: str, name: str, label: str) -> StreamEvent:
|
||||
return StreamEvent(kind="tool", phase=phase, name=name, label=label)
|
||||
|
||||
@staticmethod
|
||||
def client_tool(
|
||||
*,
|
||||
tool_call_id: str,
|
||||
name: str,
|
||||
args: dict | None,
|
||||
label: str,
|
||||
) -> StreamEvent:
|
||||
return StreamEvent(
|
||||
kind="client_tool",
|
||||
tool_call_id=tool_call_id,
|
||||
name=name,
|
||||
args=args or {},
|
||||
label=label,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def pending_client_tools() -> StreamEvent:
|
||||
return StreamEvent(kind="pending_client_tools")
|
||||
|
||||
@staticmethod
|
||||
def response_chain(response_id: str) -> StreamEvent:
|
||||
"""内部事件:落会话续链;不推给前端 SSE。"""
|
||||
return StreamEvent(kind="response_chain", response_id=response_id)
|
||||
@@ -0,0 +1,170 @@
|
||||
"""领域端口(依赖倒置)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, AsyncIterator, Protocol
|
||||
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
LlmProtocolCapability,
|
||||
LlmRuntimeConfig,
|
||||
Session,
|
||||
StreamEvent,
|
||||
UserMemory,
|
||||
)
|
||||
|
||||
|
||||
class SessionRepository(ABC):
|
||||
@abstractmethod
|
||||
async def create(self, session: Session) -> Session: ...
|
||||
|
||||
@abstractmethod
|
||||
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def list_active(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
limit: int = 50,
|
||||
*,
|
||||
scene: str | None = None,
|
||||
) -> list[Session]: ...
|
||||
|
||||
@abstractmethod
|
||||
async def find_active_by_scene_ref(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
*,
|
||||
scene: str,
|
||||
scene_ref: str,
|
||||
) -> Session | None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def update(self, session: Session) -> Session: ...
|
||||
|
||||
|
||||
class MessageRepository(ABC):
|
||||
@abstractmethod
|
||||
async def append(self, message: ChatMessage) -> ChatMessage: ...
|
||||
|
||||
@abstractmethod
|
||||
async def list_recent(
|
||||
self, company_id: int, user_id: str, thread_id: str, limit: int
|
||||
) -> list[ChatMessage]: ...
|
||||
|
||||
@abstractmethod
|
||||
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: ...
|
||||
|
||||
@abstractmethod
|
||||
async def soft_delete_by_thread(
|
||||
self, company_id: int, user_id: str, thread_id: str
|
||||
) -> int:
|
||||
"""软删某会话下全部消息,返回影响条数。"""
|
||||
...
|
||||
|
||||
|
||||
class MemoryRepository(ABC):
|
||||
@abstractmethod
|
||||
async def list_active(
|
||||
self, company_id: int, user_id: str, limit: int
|
||||
) -> list[UserMemory]: ...
|
||||
|
||||
@abstractmethod
|
||||
async def count_active(self, company_id: int, user_id: str) -> int: ...
|
||||
|
||||
@abstractmethod
|
||||
async def search(
|
||||
self, company_id: int, user_id: str, query: str, limit: int
|
||||
) -> list[UserMemory]: ...
|
||||
|
||||
@abstractmethod
|
||||
async def get_by_ids(
|
||||
self, company_id: int, user_id: str, memory_ids: list[str]
|
||||
) -> list[UserMemory]: ...
|
||||
|
||||
@abstractmethod
|
||||
async def upsert(self, memory: UserMemory) -> UserMemory: ...
|
||||
|
||||
@abstractmethod
|
||||
async def soft_delete(self, company_id: int, user_id: str, memory_id: str) -> bool: ...
|
||||
|
||||
|
||||
class LlmRuntimeCache(ABC):
|
||||
@abstractmethod
|
||||
async def get(
|
||||
self,
|
||||
company_id: int,
|
||||
provider_id: int | None = None,
|
||||
model: str | None = None,
|
||||
) -> LlmRuntimeConfig | None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def set(
|
||||
self,
|
||||
company_id: int,
|
||||
config: LlmRuntimeConfig,
|
||||
ttl_seconds: int,
|
||||
) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def delete(self, company_id: int) -> None: ...
|
||||
|
||||
|
||||
class LlmRuntimeGateway(ABC):
|
||||
"""从 Server 拉取运行时模型配置(MySQL 真相源)。"""
|
||||
|
||||
@abstractmethod
|
||||
async def fetch(
|
||||
self,
|
||||
company_id: int,
|
||||
provider_id: int | None = None,
|
||||
model: str | None = None,
|
||||
) -> LlmRuntimeConfig | None: ...
|
||||
|
||||
|
||||
class LlmProtocolCapabilityCache(ABC):
|
||||
"""缓存某提供商(或 base_url)是否支持 Responses / store。"""
|
||||
|
||||
@abstractmethod
|
||||
async def get(
|
||||
self, *, provider_id: int | None, base_url: str
|
||||
) -> LlmProtocolCapability | None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def set(
|
||||
self,
|
||||
*,
|
||||
provider_id: int | None,
|
||||
base_url: str,
|
||||
capability: LlmProtocolCapability,
|
||||
ttl_seconds: int,
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class ClientToolTurn(Protocol):
|
||||
"""一轮聊天里前端工具的回执等待:先 arm 再推 SSE,再 wait_result。"""
|
||||
|
||||
def arm(self, tool_call_id: str) -> None: ...
|
||||
|
||||
async def wait_result(self, tool_call_id: str) -> str: ...
|
||||
|
||||
|
||||
class ChatStreamer(ABC):
|
||||
"""流式生成助手回复。"""
|
||||
|
||||
@abstractmethod
|
||||
async def stream_reply(
|
||||
self,
|
||||
*,
|
||||
llm: LlmRuntimeConfig,
|
||||
history: list[ChatMessage],
|
||||
user_text: str,
|
||||
system_prompt: str,
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 4000,
|
||||
previous_response_id: str | None = None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]: ...
|
||||
Reference in New Issue
Block a user