mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-24 19:09:20 +08:00
init
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
"""对话用例:落库 + token 窗口裁剪 + 记忆工具 + 流式生成。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import AsyncIterator
|
||||
|
||||
from agent.runtime import load_tools_for_turn
|
||||
from application.client_tool_gate import BoundClientToolTurn, get_client_tool_gate
|
||||
from application.context_window import resolve_context_window, trim_history_to_budget
|
||||
from application.llm_settings_service import LlmRuntimeService
|
||||
from application.memory_service import MemoryService
|
||||
from application.session_service import SessionService
|
||||
from application.system_prompt import build_system_prompt
|
||||
from config.settings import Settings
|
||||
from domain.models import (
|
||||
Actor,
|
||||
ChatMessage,
|
||||
LlmResponseChain,
|
||||
MessageRole,
|
||||
StreamEvent,
|
||||
)
|
||||
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
|
||||
|
||||
|
||||
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,
|
||||
*,
|
||||
form_snapshot: dict | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
text = (content or "").strip()
|
||||
if not text:
|
||||
raise ValueError("消息不能为空")
|
||||
|
||||
session = await self._sessions.require_owned(actor, thread_id)
|
||||
scene = session.scene or "general"
|
||||
llm = await self._llm_runtime.resolve_runtime(
|
||||
actor.company_id,
|
||||
provider_id=session.llm_provider_id,
|
||||
model=session.llm_model,
|
||||
)
|
||||
changed = False
|
||||
if session.llm_model != llm.model:
|
||||
session.llm_model = llm.model
|
||||
changed = True
|
||||
if llm.provider_id is not None and session.llm_provider_id != llm.provider_id:
|
||||
session.llm_provider_id = llm.provider_id
|
||||
changed = True
|
||||
if changed:
|
||||
session.llm_response_chain = None
|
||||
await self._session_repo.update(session)
|
||||
|
||||
# 链是否可用由 streamer 按 store 能力决定;此处只做选型匹配
|
||||
chain_id = _usable_chain_id(session.llm_response_chain, llm)
|
||||
if session.llm_response_chain and not chain_id:
|
||||
session.llm_response_chain = None
|
||||
await self._session_repo.update(session)
|
||||
|
||||
just_saved = None
|
||||
memory_count = 0
|
||||
if scene == "general":
|
||||
just_saved = await self._memory.maybe_capture_from_user(
|
||||
actor, thread_id=thread_id, text=text
|
||||
)
|
||||
memory_count = await self._memory.count_active(actor)
|
||||
|
||||
system_prompt = build_system_prompt(
|
||||
memory_count=memory_count,
|
||||
memory_just_saved=just_saved,
|
||||
scene=scene,
|
||||
form_snapshot=form_snapshot,
|
||||
)
|
||||
|
||||
client_tools = None
|
||||
if scene == "ecom_goods_publish":
|
||||
from agent.tools.publish_ui import build_publish_client_tools
|
||||
|
||||
client_tools = build_publish_client_tools()
|
||||
|
||||
tools = await load_tools_for_turn(
|
||||
self._settings,
|
||||
actor=actor,
|
||||
memory=self._memory,
|
||||
scene=scene,
|
||||
client_tools=client_tools,
|
||||
)
|
||||
|
||||
raw_history = await self._messages.list_recent(
|
||||
actor.company_id,
|
||||
actor.user_id,
|
||||
thread_id,
|
||||
self._settings.chat_history_fetch_limit,
|
||||
)
|
||||
context_window = resolve_context_window(
|
||||
llm, fallback=self._settings.llm_default_context_window
|
||||
)
|
||||
history = trim_history_to_budget(
|
||||
raw_history,
|
||||
system_text=system_prompt,
|
||||
user_text=text,
|
||||
context_window=context_window,
|
||||
reserve_output_tokens=self._settings.context_reserve_output_tokens,
|
||||
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
|
||||
)
|
||||
max_tool_chars = max(
|
||||
500, self._settings.context_reserve_tool_tokens * 2
|
||||
)
|
||||
|
||||
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] = []
|
||||
new_response_id: str | None = None
|
||||
gate = get_client_tool_gate()
|
||||
epoch = gate.begin(thread_id)
|
||||
turn = BoundClientToolTurn(gate, thread_id, epoch)
|
||||
try:
|
||||
async for event in self._streamer.stream_reply(
|
||||
llm=llm,
|
||||
history=history,
|
||||
user_text=text,
|
||||
system_prompt=system_prompt,
|
||||
tools=tools or None,
|
||||
max_tool_result_chars=max_tool_chars,
|
||||
previous_response_id=chain_id,
|
||||
client_tool_turn=turn,
|
||||
):
|
||||
if event.kind == "response_chain" and event.response_id:
|
||||
new_response_id = event.response_id
|
||||
continue
|
||||
if event.kind == "token" and event.text:
|
||||
parts.append(event.text)
|
||||
yield event
|
||||
finally:
|
||||
gate.end(thread_id, epoch)
|
||||
|
||||
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()
|
||||
if new_response_id:
|
||||
session.llm_response_chain = LlmResponseChain(
|
||||
provider_id=llm.provider_id,
|
||||
model=llm.model,
|
||||
previous_response_id=new_response_id,
|
||||
)
|
||||
else:
|
||||
session.llm_response_chain = None
|
||||
await self._session_repo.update(session)
|
||||
|
||||
|
||||
def _usable_chain_id(chain: LlmResponseChain | None, llm) -> str | None:
|
||||
if chain is None:
|
||||
return None
|
||||
rid = (chain.previous_response_id or "").strip()
|
||||
if not rid:
|
||||
return None
|
||||
if (chain.model or "") != (llm.model or ""):
|
||||
return None
|
||||
if chain.provider_id is not None and llm.provider_id is not None:
|
||||
if int(chain.provider_id) != int(llm.provider_id):
|
||||
return None
|
||||
return rid
|
||||
@@ -0,0 +1,127 @@
|
||||
"""前端工具回执门闩:进程内按会话代次等待,供 SSE 挂起后由 POST 唤醒。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
|
||||
# 前端写入应很快返回;超时后模型拿到失败,避免 SSE 一直挂着
|
||||
_DEFAULT_TIMEOUT_SECONDS = 20.0
|
||||
|
||||
|
||||
def format_client_tool_result(ok: bool, message: str) -> str:
|
||||
"""写成模型可读的 ToolMessage。失败统一前缀,便于提示词识别。"""
|
||||
text = (message or "").strip()
|
||||
if ok:
|
||||
return text or "已写入"
|
||||
return f"写入失败:{text or '未知原因'}"
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Waiter:
|
||||
epoch: int
|
||||
future: asyncio.Future[tuple[bool, str]]
|
||||
|
||||
|
||||
class ClientToolGate:
|
||||
"""单进程等待表。多 worker 时回执可能打到别的进程,当前部署按单进程使用。"""
|
||||
|
||||
def __init__(self, timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS) -> None:
|
||||
self._timeout = timeout_seconds
|
||||
self._epoch: dict[str, int] = {}
|
||||
self._waiters: dict[tuple[str, str], _Waiter] = {}
|
||||
|
||||
def begin(self, thread_id: str) -> int:
|
||||
"""新开一轮:抬高代次,并结束该会话上一代尚未完成的等待。"""
|
||||
epoch = self._epoch.get(thread_id, 0) + 1
|
||||
self._epoch[thread_id] = epoch
|
||||
self._settle(thread_id, only_epoch=None, keep_epoch=epoch, message="本轮已取消")
|
||||
return epoch
|
||||
|
||||
def end(self, thread_id: str, epoch: int) -> None:
|
||||
"""本轮流结束或断开:只结算这一代,避免误伤已开始的下一轮。"""
|
||||
self._settle(thread_id, only_epoch=epoch, keep_epoch=None, message="本轮已取消")
|
||||
|
||||
def arm(self, thread_id: str, epoch: int, tool_call_id: str) -> None:
|
||||
"""在向浏览器推 client_tool 之前登记,避免回执先到。"""
|
||||
if self._epoch.get(thread_id) != epoch:
|
||||
return
|
||||
key = (thread_id, tool_call_id)
|
||||
loop = asyncio.get_running_loop()
|
||||
previous = self._waiters.get(key)
|
||||
if previous is not None and not previous.future.done():
|
||||
previous.future.set_result((False, "本轮已取消"))
|
||||
self._waiters[key] = _Waiter(epoch=epoch, future=loop.create_future())
|
||||
|
||||
async def wait(self, thread_id: str, epoch: int, tool_call_id: str) -> tuple[bool, str]:
|
||||
key = (thread_id, tool_call_id)
|
||||
waiter = self._waiters.get(key)
|
||||
if waiter is None or waiter.epoch != epoch:
|
||||
return False, "本轮已取消"
|
||||
future = waiter.future
|
||||
try:
|
||||
# shield:超时或断流时不把 Future 一起取消,便于区分迟到回执
|
||||
return await asyncio.wait_for(asyncio.shield(future), self._timeout)
|
||||
except asyncio.TimeoutError:
|
||||
if not future.done():
|
||||
future.set_result((False, "前端未回执"))
|
||||
return False, "前端未回执"
|
||||
finally:
|
||||
current = self._waiters.get(key)
|
||||
if current is not None and current.future is future:
|
||||
self._waiters.pop(key, None)
|
||||
|
||||
def submit(self, thread_id: str, tool_call_id: str, ok: bool, message: str) -> bool:
|
||||
"""对上当前代次的等待则唤醒。迟到或未知 id 返回 False。"""
|
||||
key = (thread_id, tool_call_id)
|
||||
waiter = self._waiters.get(key)
|
||||
epoch = self._epoch.get(thread_id)
|
||||
if waiter is None or epoch is None or waiter.epoch != epoch or waiter.future.done():
|
||||
return False
|
||||
waiter.future.set_result((bool(ok), message or ""))
|
||||
return True
|
||||
|
||||
def _settle(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
only_epoch: int | None,
|
||||
keep_epoch: int | None,
|
||||
message: str,
|
||||
) -> None:
|
||||
for key, waiter in list(self._waiters.items()):
|
||||
if key[0] != thread_id:
|
||||
continue
|
||||
if only_epoch is not None and waiter.epoch != only_epoch:
|
||||
continue
|
||||
if keep_epoch is not None and waiter.epoch == keep_epoch:
|
||||
continue
|
||||
self._waiters.pop(key, None)
|
||||
if not waiter.future.done():
|
||||
waiter.future.set_result((False, message))
|
||||
|
||||
|
||||
_gate: ClientToolGate | None = None
|
||||
|
||||
|
||||
def get_client_tool_gate() -> ClientToolGate:
|
||||
global _gate
|
||||
if _gate is None:
|
||||
_gate = ClientToolGate()
|
||||
return _gate
|
||||
|
||||
|
||||
class BoundClientToolTurn:
|
||||
"""绑定到一次 stream_chat 的代次。"""
|
||||
|
||||
def __init__(self, gate: ClientToolGate, thread_id: str, epoch: int) -> None:
|
||||
self._gate = gate
|
||||
self._thread_id = thread_id
|
||||
self._epoch = epoch
|
||||
|
||||
def arm(self, tool_call_id: str) -> None:
|
||||
self._gate.arm(self._thread_id, self._epoch, tool_call_id)
|
||||
|
||||
async def wait_result(self, tool_call_id: str) -> str:
|
||||
ok, message = await self._gate.wait(self._thread_id, self._epoch, tool_call_id)
|
||||
return format_client_tool_result(ok, message)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""上下文窗口解析与粗粒度 token 估算(非精确 tokenizer)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole
|
||||
|
||||
# 未配置且无法按模型名识别时的保守默认
|
||||
_DEFAULT_CONTEXT_WINDOW = 128_000
|
||||
|
||||
|
||||
def resolve_context_window(llm: LlmRuntimeConfig, fallback: int | None = None) -> int:
|
||||
"""生效上下文窗口:租户配置 > 模型名启发式 > 默认。"""
|
||||
if llm.context_window is not None and llm.context_window > 0:
|
||||
return int(llm.context_window)
|
||||
guessed = guess_context_window(llm.model)
|
||||
if guessed:
|
||||
return guessed
|
||||
if fallback is not None and fallback > 0:
|
||||
return fallback
|
||||
return _DEFAULT_CONTEXT_WINDOW
|
||||
|
||||
|
||||
def guess_context_window(model: str) -> int | None:
|
||||
"""按常见模型名估计 context;无法识别返回 None。"""
|
||||
m = (model or "").lower().strip()
|
||||
if not m:
|
||||
return None
|
||||
# 显式带 k 标记
|
||||
mk = re.search(r"(\d+)\s*k\b", m)
|
||||
if mk:
|
||||
return int(mk.group(1)) * 1024
|
||||
if "claude" in m:
|
||||
return 200_000
|
||||
if "gpt-4o" in m or "gpt-4.1" in m or "o1" in m or "o3" in m:
|
||||
return 128_000
|
||||
if "gpt-4-turbo" in m or "gpt-4-1106" in m or "gpt-4-0125" in m:
|
||||
return 128_000
|
||||
if "gpt-4-32k" in m:
|
||||
return 32_768
|
||||
if "gpt-3.5" in m or "gpt-35" in m:
|
||||
return 16_385
|
||||
if "deepseek" in m:
|
||||
return 128_000
|
||||
if "qwen" in m or "qwq" in m:
|
||||
return 131_072
|
||||
if "glm" in m or "moonshot" in m or "kimi" in m:
|
||||
return 128_000
|
||||
if "gemini" in m:
|
||||
return 128_000
|
||||
return None
|
||||
|
||||
|
||||
def estimate_tokens(text: str) -> int:
|
||||
"""粗估 token:偏保守(略高估),避免撑爆真实窗口。"""
|
||||
if not text:
|
||||
return 0
|
||||
# CJK 约 1.5 字/token,其余按 ~4 char/token;整体再乘 1.1
|
||||
cjk = len(re.findall(r"[\u4e00-\u9fff]", text))
|
||||
other = max(0, len(text) - cjk)
|
||||
raw = cjk / 1.5 + other / 4.0
|
||||
return max(1, int(raw * 1.1) + 1)
|
||||
|
||||
|
||||
def estimate_message_tokens(role: str, content: str) -> int:
|
||||
"""单条消息开销(含 role 包装余量)。"""
|
||||
return estimate_tokens(content) + 8
|
||||
|
||||
|
||||
def trim_history_to_budget(
|
||||
history: list[ChatMessage],
|
||||
*,
|
||||
system_text: str,
|
||||
user_text: str,
|
||||
context_window: int,
|
||||
reserve_output_tokens: int,
|
||||
reserve_tool_tokens: int,
|
||||
min_history_messages: int = 2,
|
||||
) -> list[ChatMessage]:
|
||||
"""从旧到新丢弃历史,直到落入 token 预算;保证至少保留最近若干条。"""
|
||||
if not history:
|
||||
return []
|
||||
fixed = (
|
||||
estimate_message_tokens("system", system_text)
|
||||
+ estimate_message_tokens("user", user_text)
|
||||
+ max(0, reserve_output_tokens)
|
||||
+ max(0, reserve_tool_tokens)
|
||||
)
|
||||
budget = max(512, context_window - fixed)
|
||||
keep: list[ChatMessage] = []
|
||||
used = 0
|
||||
# 从新到旧挑选
|
||||
for msg in reversed(history):
|
||||
if msg.role not in (MessageRole.USER, MessageRole.ASSISTANT):
|
||||
continue
|
||||
cost = estimate_message_tokens(msg.role.value, msg.content or "")
|
||||
if keep and used + cost > budget and len(keep) >= min_history_messages:
|
||||
break
|
||||
keep.append(msg)
|
||||
used += cost
|
||||
keep.reverse()
|
||||
return keep
|
||||
@@ -0,0 +1,65 @@
|
||||
"""租户 LLM 运行时解析:Redis → 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,
|
||||
provider_id: int | None = None,
|
||||
model: str | None = None,
|
||||
) -> LlmRuntimeConfig:
|
||||
want_model = (model or "").strip() or None
|
||||
want_provider = provider_id
|
||||
cached = await self._cache.get(company_id, want_provider, want_model)
|
||||
if cached is not None and cached.api_key:
|
||||
return cached
|
||||
|
||||
remote = await self._gateway.fetch(company_id, want_provider, want_model)
|
||||
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
|
||||
and not want_model
|
||||
and want_provider is None
|
||||
):
|
||||
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,
|
||||
provider_id=None,
|
||||
context_window=None,
|
||||
api_style="auto",
|
||||
)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=(
|
||||
"当前公司尚未配置模型 API,或所选模型未启用;"
|
||||
"请在「模型管理」中配置提供商并启用模型"
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""用户记忆用例:摘要写入、关键词检索、按需载入。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
|
||||
from config.settings import Settings
|
||||
from domain.models import Actor, MemoryKind, UserMemory
|
||||
from domain.ports import MemoryRepository
|
||||
|
||||
# 消息中出现「记住…」即写入(不必整句以此开头)
|
||||
_REMEMBER_RE = re.compile(
|
||||
r"(?:请?帮?我?记住一下?|请?记住)[::\s,,]*(.+)",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
_SUMMARY_MAX = 80
|
||||
|
||||
|
||||
def build_memory_summary(text: str) -> str:
|
||||
"""规则摘要:压缩空白并截断,供搜索与列表展示。"""
|
||||
s = re.sub(r"\s+", " ", (text or "").strip())
|
||||
if not s:
|
||||
return ""
|
||||
if len(s) <= _SUMMARY_MAX:
|
||||
return s
|
||||
return s[: _SUMMARY_MAX - 1] + "…"
|
||||
|
||||
|
||||
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,
|
||||
"summary": m.summary or build_memory_summary(m.text),
|
||||
"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 count_active(self, actor: Actor) -> int:
|
||||
return await self._repo.count_active(actor.company_id, actor.user_id)
|
||||
|
||||
async def search(
|
||||
self, actor: Actor, query: str, limit: int = 5
|
||||
) -> list[dict]:
|
||||
"""返回摘要命中列表(无正文)。"""
|
||||
rows = await self._repo.search(
|
||||
actor.company_id,
|
||||
actor.user_id,
|
||||
query,
|
||||
max(1, min(limit, 20)),
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": m.id,
|
||||
"summary": m.summary or build_memory_summary(m.text),
|
||||
"kind": m.kind.value,
|
||||
"updatedAt": m.updated_at.isoformat() + "Z",
|
||||
}
|
||||
for m in rows
|
||||
]
|
||||
|
||||
async def load(self, actor: Actor, memory_ids: list[str]) -> list[dict]:
|
||||
"""按 id 载入正文;单次最多 5 条。"""
|
||||
ids = [i for i in memory_ids if i][:5]
|
||||
rows = await self._repo.get_by_ids(actor.company_id, actor.user_id, ids)
|
||||
return [
|
||||
{
|
||||
"id": m.id,
|
||||
"summary": m.summary or build_memory_summary(m.text),
|
||||
"text": m.text,
|
||||
"kind": m.kind.value,
|
||||
}
|
||||
for m in rows
|
||||
]
|
||||
|
||||
async def save(
|
||||
self,
|
||||
actor: Actor,
|
||||
text: str,
|
||||
*,
|
||||
kind: MemoryKind = MemoryKind.FACT,
|
||||
thread_id: str | None = None,
|
||||
key: str | None = None,
|
||||
) -> dict:
|
||||
"""写入一条记忆(含规则摘要)。"""
|
||||
body = (text or "").strip()
|
||||
if not body:
|
||||
raise ValueError("记忆内容不能为空")
|
||||
body = body[:1000]
|
||||
summary = build_memory_summary(body)
|
||||
mem_key = key or ("remember:" + hashlib.sha1(body.encode("utf-8")).hexdigest()[:16])
|
||||
saved = await self._repo.upsert(
|
||||
UserMemory(
|
||||
company_id=actor.company_id,
|
||||
user_id=actor.user_id,
|
||||
kind=kind,
|
||||
key=mem_key,
|
||||
text=body,
|
||||
summary=summary,
|
||||
source_thread_id=thread_id,
|
||||
)
|
||||
)
|
||||
return {"id": saved.id, "summary": saved.summary or summary, "kind": saved.kind.value}
|
||||
|
||||
async def maybe_capture_from_user(
|
||||
self, actor: Actor, *, thread_id: str, text: str
|
||||
) -> str | None:
|
||||
"""显式「记住…」写入跨会话记忆;命中则返回写入正文,否则 None。"""
|
||||
m = _REMEMBER_RE.search((text or "").strip())
|
||||
if not m:
|
||||
return None
|
||||
body = m.group(1).strip().rstrip("。.!!")
|
||||
if not body or len(body) > 1000:
|
||||
return None
|
||||
if body in ("一下", "下"):
|
||||
return None
|
||||
result = await self.save(
|
||||
actor,
|
||||
body,
|
||||
kind=MemoryKind.PREFERENCE,
|
||||
thread_id=thread_id,
|
||||
)
|
||||
return body if result else None
|
||||
@@ -0,0 +1,172 @@
|
||||
"""会话用例。"""
|
||||
|
||||
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 MessageRepository, SessionRepository
|
||||
|
||||
|
||||
class SessionService:
|
||||
def __init__(
|
||||
self,
|
||||
sessions: SessionRepository,
|
||||
llm_runtime: LlmRuntimeService | None = None,
|
||||
messages: MessageRepository | None = None,
|
||||
) -> None:
|
||||
self._sessions = sessions
|
||||
self._llm_runtime = llm_runtime
|
||||
self._messages = messages
|
||||
|
||||
async def create(
|
||||
self,
|
||||
actor: Actor,
|
||||
title: str | None = None,
|
||||
llm_provider_id: int | None = None,
|
||||
llm_model: str | None = None,
|
||||
*,
|
||||
scene: str | None = None,
|
||||
scene_ref: str | None = None,
|
||||
) -> Session:
|
||||
now = datetime.utcnow()
|
||||
model = (llm_model or "").strip() or None
|
||||
provider_id = llm_provider_id
|
||||
if (not model or provider_id is None) and self._llm_runtime is not None:
|
||||
try:
|
||||
rt = await self._llm_runtime.resolve_runtime(
|
||||
actor.company_id,
|
||||
provider_id=provider_id,
|
||||
model=model,
|
||||
)
|
||||
model = rt.model or model
|
||||
provider_id = rt.provider_id if rt.provider_id is not None else provider_id
|
||||
except Exception:
|
||||
pass
|
||||
scene_value = (scene or "general").strip() or "general"
|
||||
ref = (scene_ref or "").strip() or 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,
|
||||
scene=scene_value,
|
||||
scene_ref=ref,
|
||||
llm_provider_id=provider_id,
|
||||
llm_model=model,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
return await self._sessions.create(session)
|
||||
|
||||
async def list_mine(
|
||||
self, actor: Actor, *, scene: str | None = None
|
||||
) -> list[Session]:
|
||||
return await self._sessions.list_active(
|
||||
actor.company_id, actor.user_id, scene=scene
|
||||
)
|
||||
|
||||
async def find_by_scene_ref(
|
||||
self, actor: Actor, *, scene: str, scene_ref: str
|
||||
) -> Session | None:
|
||||
"""同一 scene_ref 复用已有活跃会话(一草稿一会话)。"""
|
||||
return await self._sessions.find_active_by_scene_ref(
|
||||
actor.company_id,
|
||||
actor.user_id,
|
||||
scene=scene,
|
||||
scene_ref=scene_ref,
|
||||
)
|
||||
|
||||
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 rebind_scene_ref(
|
||||
self,
|
||||
actor: Actor,
|
||||
thread_id: str,
|
||||
*,
|
||||
scene_ref: str,
|
||||
title: str | None = None,
|
||||
) -> Session:
|
||||
"""把未落库会话(scene_ref=local-*)改绑到稳定业务键(如系统草稿 ID)。"""
|
||||
new_ref = (scene_ref or "").strip()
|
||||
if not new_ref:
|
||||
raise ValueError("scene_ref 不能为空")
|
||||
if new_ref.startswith("local-"):
|
||||
raise ValueError("不能改绑到临时 local 键")
|
||||
|
||||
session = await self.require_owned(actor, thread_id)
|
||||
if session.scene_ref == new_ref:
|
||||
if title is not None:
|
||||
session.title = title.strip() or session.title
|
||||
return await self._sessions.update(session)
|
||||
return session
|
||||
|
||||
current = (session.scene_ref or "").strip()
|
||||
if current and not current.startswith("local-"):
|
||||
raise ValueError("仅未落库会话可改绑 scene_ref")
|
||||
|
||||
existing = await self.find_by_scene_ref(
|
||||
actor, scene=session.scene or "general", scene_ref=new_ref
|
||||
)
|
||||
if existing is not None and existing.thread_id != thread_id:
|
||||
raise ValueError("该业务对象已有关联会话")
|
||||
|
||||
session.scene_ref = new_ref
|
||||
if title is not None:
|
||||
session.title = title.strip() or session.title
|
||||
return await self._sessions.update(session)
|
||||
|
||||
async def update_llm_selection(
|
||||
self,
|
||||
actor: Actor,
|
||||
thread_id: str,
|
||||
*,
|
||||
llm_provider_id: int,
|
||||
llm_model: str,
|
||||
) -> Session:
|
||||
model = (llm_model or "").strip()
|
||||
if not model:
|
||||
raise ValueError("模型不能为空")
|
||||
if llm_provider_id is None or int(llm_provider_id) <= 0:
|
||||
raise ValueError("提供商不能为空")
|
||||
session = await self.require_owned(actor, thread_id)
|
||||
switched = (
|
||||
session.llm_provider_id != int(llm_provider_id)
|
||||
or (session.llm_model or "") != model
|
||||
)
|
||||
session.llm_provider_id = int(llm_provider_id)
|
||||
session.llm_model = model
|
||||
if switched:
|
||||
# 切换选型后厂商侧链不可复用
|
||||
session.llm_response_chain = None
|
||||
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)
|
||||
|
||||
async def delete(self, actor: Actor, thread_id: str) -> Session:
|
||||
"""软删会话,并级联软删该线程消息。"""
|
||||
session = await self.require_owned(actor, thread_id)
|
||||
session.status = SessionStatus.DELETED
|
||||
session.llm_response_chain = None
|
||||
session.summary = None
|
||||
saved = await self._sessions.update(session)
|
||||
if self._messages is not None:
|
||||
await self._messages.soft_delete_by_thread(
|
||||
actor.company_id, actor.user_id, thread_id
|
||||
)
|
||||
return saved
|
||||
@@ -0,0 +1,88 @@
|
||||
"""对话 system 提示组装(应用策略,供裁剪预算与流式共用)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from domain.models import SCENE_ECOM_GOODS_PUBLISH, SCENE_GENERAL
|
||||
|
||||
_BASE_SYSTEM = (
|
||||
"你是电商 DMB 系统的经营助手。回答简洁、可执行、结论先行。"
|
||||
"需要经营数据时优先调用可用工具。"
|
||||
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
|
||||
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
|
||||
"【本会话上下文】请求里已包含本会话近期的用户与助手原文,你可以直接看见并引用;"
|
||||
"禁止声称「只收到当前一句」或「前面几轮不会带过来」——那是错误描述。"
|
||||
"【长期记忆】跨会话的用户级记忆不会自动注入;需要称呼、偏好或用户事实时:"
|
||||
"先 memory_search,必要时再 memory_load;禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
||||
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
|
||||
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
|
||||
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
|
||||
"用户要求记住:可用 memory_save,或系统提示「本轮已写入」时只简短确认内容。"
|
||||
"用户说近 N 天、昨天、本周、本月等相对日期时,先调用 get_current_time,"
|
||||
"用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查数,不要向用户索要日期范围。"
|
||||
"用户用名称或编码指代店铺、商品、SKU 时,先调用 catalog_search;"
|
||||
"恰好一条就用返回的 id 继续查数;多条只列名称和编码让用户选。"
|
||||
"用户消息含 [引用] 且带 id= 时,直接用这些 id,不必再搜索,也不要向用户复述 id。"
|
||||
"禁止向用户索要店铺 ID、商品 ID 或 SKU ID。"
|
||||
"若只给了引用、没有具体问题,按近 7 天概览回答该对象。"
|
||||
"若工具失败或无权限,请说明原因并给出可操作建议。"
|
||||
)
|
||||
|
||||
_PUBLISH_SYSTEM = (
|
||||
"你是电商 DMB 的拼多多商品发布助手,只在当前系统草稿页改表。"
|
||||
"能写的工具:ui_patch_basic(标题、描述、参考价、满两件折扣、发货时限、"
|
||||
"假一赔十/7天无理由/预售/二手、运费模板)、ui_set_spec_axes(规格轴)、"
|
||||
"ui_patch_skus(按 outSkuSn 改单买价、拼单价、库存、重量)、ui_patch_props(类目属性)。"
|
||||
"每次只传要改的字段,未传的保持原样。"
|
||||
"商品标题字数:汉字算 2、英文数字算 1,合计最多 60(约 30 汉字);生成或改写标题时自行压缩到上限内,不要写超再指望页面截断。"
|
||||
"运费模板 ID 必须来自快照 costTemplates;发货时限只能用快照里的秒数;"
|
||||
"类目属性枚举用 goodsProperties 里的 vid 或文案,多选英文逗号分隔。"
|
||||
"不能改店铺、叶子类目、轮播图、详情图、SKU 缩略图;用户要求这些时用一句话说明对话里改不了。"
|
||||
"【当前发布表单】是本轮开始时的页面内容。改表必须调用上述工具,不要只口头说已修改。"
|
||||
"工具返回是页面当时的写入结果:不以「写入失败」开头即已显示在编辑器里,无需用户刷新或再核对。"
|
||||
"以「写入失败」开头时只说明原因,不要声称已经改好。"
|
||||
"商家编码 outSkuSn 是 SKU 唯一身份,规格文案只是描述。只改同一维的名称或取值时只传 axes;"
|
||||
"改变组合结构(如 2×2→1×4)时必须带 skuAssignments,把表单里已有的 outSkuSn 挂到新 values 上,勿编造编码。"
|
||||
"用户指定了标题或规格怎么写,就按用户的写。"
|
||||
"用户只说改标题、改规格名、改某个规格值时,直接改这一处,不要先搜渠道商品,也不要改别的字段。"
|
||||
"用户要整体编辑、完善草稿、按 SKU 填写时:表单 skuRows 里已有 outSkuSn 的,先对每个编码调用 catalog_sku_detail,再改表。"
|
||||
"用返回的 name、attrs、specCombinationKey、productName 写规格文案、类目属性和标题;容量、斤、千克能换算成克的,直接写入重量。"
|
||||
"重量为 1 克、规格值像「10个」「9」这类占位,视为无效,用查到的资料覆盖,不要保留并向用户求正确值。"
|
||||
"内部 SKU 没有单买价和拼单价。规格和重量能从资料得出就必须写入,不要和售价一起追问;只有售价确实没有时,才单独问一句。"
|
||||
"只有用户明确要求参考本店在售、查重或模仿某条时,才用 pdd_goods_search / pdd_goods_detail(本地已同步商品)。"
|
||||
"不要处理图片。"
|
||||
"对用户只报结论,一两句:给出改完的标题或规格名即可。"
|
||||
"不要复述工具名、回执原文、字数统计、查了几条、竞品标题全文或改写策略,除非用户问为什么这样改。"
|
||||
"不要主动列 SKU 编码表,不要给没问过的下一版备选,不要让用户刷新、核对,或说「如果还是旧的再告诉我」。"
|
||||
"禁止向用户索要或复述数字 ID。"
|
||||
)
|
||||
|
||||
|
||||
def build_system_prompt(
|
||||
*,
|
||||
memory_count: int = 0,
|
||||
memory_just_saved: str | None = None,
|
||||
scene: str = SCENE_GENERAL,
|
||||
form_snapshot: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
if (scene or SCENE_GENERAL).strip() == SCENE_ECOM_GOODS_PUBLISH:
|
||||
snap = form_snapshot if isinstance(form_snapshot, dict) else {}
|
||||
snap_text = json.dumps(snap, ensure_ascii=False, default=str)
|
||||
# 控制体积,避免拖垮上下文
|
||||
if len(snap_text) > 12000:
|
||||
snap_text = snap_text[:12000] + "…(截断)"
|
||||
return (
|
||||
f"{_PUBLISH_SYSTEM}\n\n【当前发布表单】\n{snap_text}"
|
||||
)
|
||||
|
||||
system = _BASE_SYSTEM
|
||||
if memory_count > 0:
|
||||
system += (
|
||||
f"\n\n当前用户约有 {memory_count} 条长期记忆,"
|
||||
"需要时用 memory_search / memory_load。"
|
||||
)
|
||||
if memory_just_saved:
|
||||
system += f"\n\n【本轮已写入长期记忆】{memory_just_saved}"
|
||||
return system
|
||||
Reference in New Issue
Block a user