mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-24 23:09:20 +08:00
init
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""基础设施:鉴权、LLM、MCP、持久化适配。"""
|
||||
@@ -0,0 +1,35 @@
|
||||
"""JWT 校验(对齐 Java JwtUtils:HS512,sub=userId,claim companyId)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import jwt
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from config.settings import Settings
|
||||
from domain.models import Actor
|
||||
|
||||
|
||||
def parse_actor(settings: Settings, token: str) -> Actor:
|
||||
try:
|
||||
payload: dict[str, Any] = jwt.decode(
|
||||
token,
|
||||
settings.jwt_secret,
|
||||
algorithms=[a.strip() for a in settings.jwt_algorithms.split(",") if a.strip()],
|
||||
options={"require": ["sub", "exp"]},
|
||||
)
|
||||
except jwt.PyJWTError as e:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"无效令牌: {e}") from e
|
||||
|
||||
user_id = payload.get("sub")
|
||||
company_id = payload.get("companyId")
|
||||
if not user_id or company_id is None:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="令牌缺少用户或公司信息")
|
||||
|
||||
return Actor(
|
||||
user_id=str(user_id),
|
||||
company_id=int(company_id),
|
||||
company_role=payload.get("companyRole"),
|
||||
is_super=bool(payload.get("super", False)),
|
||||
)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""协议偏好与错误分类:先验缓存 + 运行时探测回退(不写死主机)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from domain.models import LlmProtocolCapability
|
||||
|
||||
|
||||
def normalize_api_style(raw: str | None) -> str:
|
||||
s = (raw or "auto").strip().lower()
|
||||
if s in ("auto", "completions", "responses"):
|
||||
return s
|
||||
return "auto"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProtocolAttempt:
|
||||
"""单次调用策略。"""
|
||||
|
||||
use_responses: bool
|
||||
use_store: bool
|
||||
use_chain: bool # 是否只发增量 + previous_response_id(须 store 已证实)
|
||||
|
||||
|
||||
def plan_protocol_attempts(
|
||||
api_style: str | None,
|
||||
cap: LlmProtocolCapability | None,
|
||||
*,
|
||||
has_chain_id: bool,
|
||||
) -> list[ProtocolAttempt]:
|
||||
"""
|
||||
同轮探测顺序(未产出 token 前可依次尝试):
|
||||
|
||||
- store 已证实:Responses+store,有链则增量续聊
|
||||
- store 未知:Responses+store + **Mongo 全量**,成功后再语义探测
|
||||
- store 证伪:先 **无状态 Responses + Mongo 全量**,失败再 **Completions**
|
||||
- Responses 不可用:Completions
|
||||
"""
|
||||
style = normalize_api_style(api_style)
|
||||
cap = cap or LlmProtocolCapability()
|
||||
|
||||
if style == "completions":
|
||||
return [ProtocolAttempt(False, False, False)]
|
||||
|
||||
attempts: list[ProtocolAttempt] = []
|
||||
|
||||
if cap.store is False:
|
||||
# 无真实 store:无状态 Responses(全量历史)→ Completions
|
||||
if cap.responses is not False:
|
||||
attempts.append(ProtocolAttempt(True, False, False))
|
||||
attempts.append(ProtocolAttempt(False, False, False))
|
||||
return _dedupe(attempts)
|
||||
|
||||
if cap.responses is not False:
|
||||
if cap.store is True:
|
||||
attempts.append(
|
||||
ProtocolAttempt(True, True, use_chain=bool(has_chain_id))
|
||||
)
|
||||
# 有链失败时可降到同协议全量
|
||||
attempts.append(ProtocolAttempt(True, True, use_chain=False))
|
||||
else:
|
||||
# store 未知:Responses+store,必须全量历史,禁止 use_chain
|
||||
attempts.append(ProtocolAttempt(True, True, use_chain=False))
|
||||
attempts.append(ProtocolAttempt(True, False, False))
|
||||
|
||||
# Completions 兜底
|
||||
if style == "auto" or cap.responses is False:
|
||||
attempts.append(ProtocolAttempt(False, False, False))
|
||||
elif style == "responses" and cap.responses is False:
|
||||
attempts.append(ProtocolAttempt(False, False, False))
|
||||
|
||||
return _dedupe(attempts) or [ProtocolAttempt(False, False, False)]
|
||||
|
||||
|
||||
def _dedupe(attempts: list[ProtocolAttempt]) -> list[ProtocolAttempt]:
|
||||
seen: set[tuple[bool, bool, bool]] = set()
|
||||
out: list[ProtocolAttempt] = []
|
||||
for a in attempts:
|
||||
key = (a.use_responses, a.use_store, a.use_chain)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(a)
|
||||
return out
|
||||
|
||||
|
||||
def classify_protocol_error(exc: BaseException) -> str:
|
||||
"""返回: store | responses | chain | other。"""
|
||||
text = str(exc).lower()
|
||||
status = getattr(exc, "status_code", None) or getattr(
|
||||
getattr(exc, "response", None), "status_code", None
|
||||
)
|
||||
|
||||
if "previous_response_id" in text or "previous response" in text:
|
||||
return "chain"
|
||||
if status == 400 and "response" in text and "not found" in text:
|
||||
return "chain"
|
||||
|
||||
if "store" in text and any(
|
||||
n in text
|
||||
for n in (
|
||||
"unsupported",
|
||||
"unknown",
|
||||
"unrecognized",
|
||||
"invalid",
|
||||
"not support",
|
||||
"not supported",
|
||||
)
|
||||
):
|
||||
return "store"
|
||||
|
||||
if status in (404, 405):
|
||||
return "responses"
|
||||
responses_needles = (
|
||||
"/responses",
|
||||
"responses api",
|
||||
"unknown endpoint",
|
||||
"not implemented",
|
||||
"invalid pathname",
|
||||
"no route",
|
||||
)
|
||||
if any(n in text for n in responses_needles):
|
||||
return "responses"
|
||||
if status == 400 and ("responses" in text or "response.create" in text):
|
||||
return "responses"
|
||||
|
||||
return "other"
|
||||
@@ -0,0 +1,503 @@
|
||||
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。
|
||||
|
||||
优先 Responses+store → Responses store=false → Completions;
|
||||
能力结果写入 Redis,不按主机写死。未产出 token 前可同轮回退。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
from agent.tools.labels import tool_status_label
|
||||
from agent.tools.publish_ui import is_client_tool_name
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
LlmProtocolCapability,
|
||||
LlmRuntimeConfig,
|
||||
MessageRole,
|
||||
StreamEvent,
|
||||
)
|
||||
from domain.ports import ChatStreamer, ClientToolTurn, LlmProtocolCapabilityCache
|
||||
from infrastructure.llm.api_style import (
|
||||
ProtocolAttempt,
|
||||
classify_protocol_error,
|
||||
normalize_api_style,
|
||||
plan_protocol_attempts,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_UNSET = object()
|
||||
|
||||
|
||||
class OpenAICompatibleStreamer(ChatStreamer):
|
||||
def __init__(
|
||||
self,
|
||||
capability_cache: LlmProtocolCapabilityCache | None = None,
|
||||
*,
|
||||
capability_ttl_seconds: int = 604800,
|
||||
) -> None:
|
||||
self._cap_cache = capability_cache
|
||||
self._cap_ttl = capability_ttl_seconds
|
||||
|
||||
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 = 8000,
|
||||
previous_response_id: str | None = None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
chain_id = (previous_response_id or "").strip() or None
|
||||
style = normalize_api_style(llm.api_style)
|
||||
# 未知 store 时先做语义探测(能否靠 previous_response_id 记住上下文)
|
||||
cap = await self._ensure_protocol_capability(llm, style)
|
||||
attempts = plan_protocol_attempts(
|
||||
llm.api_style, cap, has_chain_id=bool(chain_id)
|
||||
)
|
||||
|
||||
i = 0
|
||||
while i < len(attempts):
|
||||
attempt = attempts[i]
|
||||
# 仅缓存已证实 store=true 时才丢历史、纯续链
|
||||
use_chain_id = (
|
||||
chain_id if (attempt.use_chain and cap and cap.store is True) else None
|
||||
)
|
||||
logger.warning(
|
||||
"LLM attempt model=%s responses=%s store=%s chain=%s hist=%s api_style=%s",
|
||||
llm.model,
|
||||
attempt.use_responses,
|
||||
attempt.use_store,
|
||||
bool(use_chain_id),
|
||||
len(history),
|
||||
style,
|
||||
)
|
||||
yielded_any = False
|
||||
got_chain_id: str | None = None
|
||||
try:
|
||||
async for event in self._stream_once(
|
||||
llm=llm,
|
||||
history=history,
|
||||
user_text=user_text,
|
||||
system_prompt=system_prompt,
|
||||
tools=tools,
|
||||
max_tool_result_chars=max_tool_result_chars,
|
||||
use_responses=attempt.use_responses,
|
||||
use_store=attempt.use_store,
|
||||
previous_response_id=use_chain_id,
|
||||
client_tool_turn=client_tool_turn,
|
||||
):
|
||||
if event.kind == "token" and event.text:
|
||||
yielded_any = True
|
||||
if event.kind == "response_chain" and event.response_id:
|
||||
got_chain_id = event.response_id
|
||||
continue
|
||||
yield event
|
||||
|
||||
if attempt.use_responses:
|
||||
if use_chain_id:
|
||||
# 已证实 store 且本轮续链成功
|
||||
await self._update_cap(llm, responses=True, store=True)
|
||||
if got_chain_id:
|
||||
yield StreamEvent.response_chain(got_chain_id)
|
||||
elif attempt.use_store:
|
||||
# store 未证实或待刷新:本轮是全量历史;语义探测真伪
|
||||
need_probe = cap is None or cap.store is not True
|
||||
if need_probe:
|
||||
store_ok = await self._probe_store_semantic(llm)
|
||||
await self._update_cap(
|
||||
llm, responses=True, store=store_ok
|
||||
)
|
||||
cap = LlmProtocolCapability(
|
||||
responses=True, store=store_ok
|
||||
)
|
||||
if store_ok and got_chain_id:
|
||||
yield StreamEvent.response_chain(got_chain_id)
|
||||
else:
|
||||
await self._update_cap(llm, responses=True, store=True)
|
||||
if got_chain_id:
|
||||
yield StreamEvent.response_chain(got_chain_id)
|
||||
else:
|
||||
# Responses 无 store:能通端点但不持久
|
||||
await self._update_cap(llm, responses=True, store=False)
|
||||
cap = LlmProtocolCapability(responses=True, store=False)
|
||||
else:
|
||||
# Completions:若已知有 Responses 只是无 store,不要把 responses 打成 false
|
||||
if cap is not None and cap.responses is True and cap.store is False:
|
||||
await self._update_cap(llm, responses=True, store=False)
|
||||
elif cap is not None and cap.store is False:
|
||||
await self._update_cap(llm, responses=cap.responses, store=False)
|
||||
else:
|
||||
await self._update_cap(llm, responses=False, store=False)
|
||||
cap = LlmProtocolCapability(responses=False, store=False)
|
||||
return
|
||||
except Exception as e: # noqa: BLE001
|
||||
if yielded_any:
|
||||
raise
|
||||
kind = classify_protocol_error(e)
|
||||
logger.warning(
|
||||
"LLM attempt failed kind=%s model=%s err=%s",
|
||||
kind,
|
||||
llm.model,
|
||||
e,
|
||||
)
|
||||
if kind == "chain" and use_chain_id:
|
||||
await self._update_cap(llm, responses=True, store=False)
|
||||
cap = LlmProtocolCapability(responses=True, store=False)
|
||||
nxt = ProtocolAttempt(True, False, False)
|
||||
if nxt not in attempts[i + 1 :]:
|
||||
attempts.insert(i + 1, nxt)
|
||||
i += 1
|
||||
continue
|
||||
if kind == "store" and attempt.use_responses and attempt.use_store:
|
||||
await self._update_cap(llm, responses=True, store=False)
|
||||
cap = LlmProtocolCapability(responses=True, store=False)
|
||||
nxt = ProtocolAttempt(True, False, False)
|
||||
if nxt not in attempts[i + 1 :]:
|
||||
attempts.insert(i + 1, nxt)
|
||||
i += 1
|
||||
continue
|
||||
if kind == "responses" and attempt.use_responses:
|
||||
await self._update_cap(llm, responses=False, store=False)
|
||||
cap = LlmProtocolCapability(responses=False, store=False)
|
||||
nxt = ProtocolAttempt(False, False, False)
|
||||
if nxt not in attempts[i + 1 :]:
|
||||
attempts.insert(i + 1, nxt)
|
||||
i += 1
|
||||
continue
|
||||
if i + 1 < len(attempts):
|
||||
i += 1
|
||||
continue
|
||||
if style == "responses" and attempt.use_responses:
|
||||
attempts.append(ProtocolAttempt(False, False, False))
|
||||
i += 1
|
||||
continue
|
||||
raise
|
||||
i += 1 # pragma: no cover
|
||||
|
||||
async def _ensure_protocol_capability(
|
||||
self, llm: LlmRuntimeConfig, style: str
|
||||
) -> LlmProtocolCapability | None:
|
||||
"""读取能力缓存;completions 强制走 Completions,不探测。"""
|
||||
if style == "completions":
|
||||
return LlmProtocolCapability(responses=False, store=False)
|
||||
return await self._load_cap(llm)
|
||||
|
||||
async def _load_cap(self, llm: LlmRuntimeConfig) -> LlmProtocolCapability | None:
|
||||
if self._cap_cache is None:
|
||||
return None
|
||||
try:
|
||||
return await self._cap_cache.get(
|
||||
provider_id=llm.provider_id, base_url=llm.base_url
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("读取协议能力缓存失败")
|
||||
return None
|
||||
|
||||
async def _update_cap(
|
||||
self,
|
||||
llm: LlmRuntimeConfig,
|
||||
*,
|
||||
responses: bool | None | object = _UNSET,
|
||||
store: bool | None | object = _UNSET,
|
||||
) -> None:
|
||||
"""更新能力缓存;参数为 _UNSET 表示不改该字段,显式 None 表示未知。"""
|
||||
if self._cap_cache is None:
|
||||
return
|
||||
try:
|
||||
prev = await self._cap_cache.get(
|
||||
provider_id=llm.provider_id, base_url=llm.base_url
|
||||
) or LlmProtocolCapability()
|
||||
new_responses = (
|
||||
prev.responses if responses is _UNSET else responses # type: ignore[arg-type]
|
||||
)
|
||||
new_store = prev.store if store is _UNSET else store # type: ignore[arg-type]
|
||||
await self._cap_cache.set(
|
||||
provider_id=llm.provider_id,
|
||||
base_url=llm.base_url,
|
||||
capability=LlmProtocolCapability(
|
||||
responses=new_responses, # type: ignore[arg-type]
|
||||
store=new_store, # type: ignore[arg-type]
|
||||
),
|
||||
ttl_seconds=self._cap_ttl,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("写入协议能力缓存失败")
|
||||
|
||||
async def _probe_store_semantic(self, llm: LlmRuntimeConfig) -> bool:
|
||||
"""
|
||||
语义探测:先写入密钥,再用 previous_response_id 且不带历史追问。
|
||||
能答对密钥 → 真支持 store 续链;否则(报错或静默丢上下文)→ false。
|
||||
"""
|
||||
secret = "ALPHA7X"
|
||||
try:
|
||||
model = ChatOpenAI(
|
||||
api_key=llm.api_key,
|
||||
base_url=llm.base_url,
|
||||
model=llm.model,
|
||||
temperature=0,
|
||||
streaming=False,
|
||||
default_headers=llm.extra_headers or None,
|
||||
use_responses_api=True,
|
||||
output_version="responses/v1",
|
||||
store=True,
|
||||
use_previous_response_id=True,
|
||||
)
|
||||
first = await model.ainvoke(
|
||||
[
|
||||
HumanMessage(
|
||||
content=(
|
||||
f"这是接口能力测试。请记住密钥:{secret}。"
|
||||
"只回复一个词:OK"
|
||||
)
|
||||
)
|
||||
]
|
||||
)
|
||||
rid = _response_id_of(first)
|
||||
if not rid:
|
||||
logger.info("store 语义探测失败:首轮无 response.id model=%s", llm.model)
|
||||
return False
|
||||
second = await model.ainvoke(
|
||||
[
|
||||
HumanMessage(
|
||||
content="接口能力测试续问:刚才的密钥是什么?只回复密钥本身。"
|
||||
)
|
||||
],
|
||||
previous_response_id=rid,
|
||||
)
|
||||
text = _chunk_text(getattr(second, "content", None)).upper()
|
||||
ok = secret in text.replace(" ", "").replace("-", "")
|
||||
if not ok:
|
||||
logger.info(
|
||||
"store 语义探测未通过(静默丢上下文)model=%s reply=%s",
|
||||
llm.model,
|
||||
text[:80],
|
||||
)
|
||||
return ok
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.info(
|
||||
"store 语义探测异常 model=%s kind=%s err=%s",
|
||||
llm.model,
|
||||
classify_protocol_error(e),
|
||||
e,
|
||||
)
|
||||
return False
|
||||
|
||||
async def _stream_once(
|
||||
self,
|
||||
*,
|
||||
llm: LlmRuntimeConfig,
|
||||
history: list[ChatMessage],
|
||||
user_text: str,
|
||||
system_prompt: str,
|
||||
tools: list[Any] | None,
|
||||
max_tool_result_chars: int,
|
||||
use_responses: bool,
|
||||
use_store: bool,
|
||||
previous_response_id: str | None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
kwargs: dict[str, Any] = {
|
||||
"api_key": llm.api_key,
|
||||
"base_url": llm.base_url,
|
||||
"model": llm.model,
|
||||
"temperature": 0.3,
|
||||
"streaming": True,
|
||||
"default_headers": llm.extra_headers or None,
|
||||
"use_responses_api": use_responses,
|
||||
}
|
||||
if use_responses:
|
||||
kwargs["output_version"] = "responses/v1"
|
||||
kwargs["store"] = use_store
|
||||
# 仅真正续链时打开;否则 LangChain 可能按 AIMessage.id 截断历史
|
||||
kwargs["use_previous_response_id"] = bool(
|
||||
previous_response_id and use_store
|
||||
)
|
||||
|
||||
model = ChatOpenAI(**kwargs)
|
||||
if previous_response_id and use_store:
|
||||
# 已证实 store:只发本轮,靠 previous_response_id 续上下文
|
||||
messages: list[Any] = [
|
||||
SystemMessage(content=system_prompt),
|
||||
HumanMessage(content=user_text),
|
||||
]
|
||||
first_extra: dict[str, Any] = {
|
||||
"previous_response_id": previous_response_id
|
||||
}
|
||||
else:
|
||||
# 无 store / Completions / 未证实:Mongo 全量历史 + 本轮
|
||||
messages = [SystemMessage(content=system_prompt)]
|
||||
for m in history:
|
||||
if m.role == MessageRole.USER:
|
||||
messages.append(HumanMessage(content=m.content))
|
||||
elif m.role == MessageRole.ASSISTANT:
|
||||
messages.append(AIMessage(content=m.content))
|
||||
messages.append(HumanMessage(content=user_text))
|
||||
first_extra = {}
|
||||
logger.warning(
|
||||
"LLM pack full history lc_messages=%s hist_rows=%s preview=%s",
|
||||
len(messages),
|
||||
len(history),
|
||||
[
|
||||
(
|
||||
m.role.value if hasattr(m, "role") else type(m).__name__,
|
||||
(getattr(m, "content", None) or "")[:40],
|
||||
)
|
||||
for m in (
|
||||
history[-4:] if len(history) > 4 else history
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
last_response_id: str | None = None
|
||||
|
||||
if not tools:
|
||||
async for chunk in model.astream(messages, **first_extra):
|
||||
last_response_id = _response_id_of(chunk) or last_response_id
|
||||
text = _chunk_text(chunk.content)
|
||||
if text:
|
||||
yield StreamEvent.token(text)
|
||||
if use_store and last_response_id:
|
||||
yield StreamEvent.response_chain(last_response_id)
|
||||
return
|
||||
|
||||
bound = model.bind_tools(tools)
|
||||
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
|
||||
tool_cap = max(500, max_tool_result_chars)
|
||||
for round_idx in range(5):
|
||||
gathered = None
|
||||
saw_tool = False
|
||||
call_extra = first_extra if round_idx == 0 else {}
|
||||
async for chunk in bound.astream(messages, **call_extra):
|
||||
gathered = chunk if gathered is None else gathered + chunk
|
||||
if getattr(chunk, "tool_call_chunks", None) or getattr(
|
||||
chunk, "tool_calls", None
|
||||
):
|
||||
saw_tool = True
|
||||
continue
|
||||
if saw_tool:
|
||||
continue
|
||||
text = _chunk_text(getattr(chunk, "content", None))
|
||||
if text:
|
||||
yield StreamEvent.token(text)
|
||||
|
||||
if gathered is None:
|
||||
yield StreamEvent.token("(模型未返回内容)")
|
||||
if use_store and last_response_id:
|
||||
yield StreamEvent.response_chain(last_response_id)
|
||||
return
|
||||
|
||||
last_response_id = _response_id_of(gathered) or last_response_id
|
||||
messages.append(gathered)
|
||||
tool_calls = getattr(gathered, "tool_calls", None) or []
|
||||
if not tool_calls:
|
||||
if use_store and last_response_id:
|
||||
yield StreamEvent.response_chain(last_response_id)
|
||||
return
|
||||
|
||||
seen: set[str] = set()
|
||||
for tc in tool_calls:
|
||||
name = tc.get("name") or ""
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
yield StreamEvent.tool(
|
||||
phase="start",
|
||||
name=name,
|
||||
label=tool_status_label(name),
|
||||
)
|
||||
|
||||
for tc in tool_calls:
|
||||
name = tc.get("name") or ""
|
||||
args = tc.get("args") or {}
|
||||
call_id = tc.get("id") or name
|
||||
try:
|
||||
if is_client_tool_name(name):
|
||||
# 占位函数不代表页面已写入;先登记等待再推事件,回执到达后才进 ToolMessage
|
||||
tool_args = args if isinstance(args, dict) else {}
|
||||
if client_tool_turn is None:
|
||||
result = "写入失败:前端回执通道未配置"
|
||||
else:
|
||||
client_tool_turn.arm(str(call_id))
|
||||
yield StreamEvent.client_tool(
|
||||
tool_call_id=str(call_id),
|
||||
name=name,
|
||||
args=tool_args,
|
||||
label=tool_status_label(name),
|
||||
)
|
||||
result = await client_tool_turn.wait_result(str(call_id))
|
||||
else:
|
||||
tool = tool_map.get(name)
|
||||
if tool is None:
|
||||
result = f"未知工具: {name}"
|
||||
else:
|
||||
raw = await tool.ainvoke(args)
|
||||
result = (
|
||||
raw
|
||||
if isinstance(raw, str)
|
||||
else json.dumps(raw, ensure_ascii=False, default=str)
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
result = f"工具执行失败: {e}"
|
||||
messages.append(
|
||||
ToolMessage(content=str(result)[:tool_cap], tool_call_id=call_id)
|
||||
)
|
||||
|
||||
for name in seen:
|
||||
yield StreamEvent.tool(
|
||||
phase="end",
|
||||
name=name,
|
||||
label=tool_status_label(name),
|
||||
)
|
||||
|
||||
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
|
||||
if use_store and last_response_id:
|
||||
yield StreamEvent.response_chain(last_response_id)
|
||||
|
||||
|
||||
def _response_id_of(msg: Any) -> str | None:
|
||||
meta = getattr(msg, "response_metadata", None) or {}
|
||||
if isinstance(meta, dict):
|
||||
rid = meta.get("id")
|
||||
if isinstance(rid, str) and rid.strip():
|
||||
return rid.strip()
|
||||
mid = getattr(msg, "id", None)
|
||||
if isinstance(mid, str) and mid.startswith("resp_"):
|
||||
return mid
|
||||
return None
|
||||
|
||||
|
||||
def _chunk_text(content: Any) -> str:
|
||||
"""兼容 Completions 字符串与 Responses 结构化 content 块。"""
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for part in content:
|
||||
if isinstance(part, str):
|
||||
parts.append(part)
|
||||
continue
|
||||
if not isinstance(part, dict):
|
||||
text = getattr(part, "text", None)
|
||||
ptype = getattr(part, "type", None)
|
||||
if text and ptype in (None, "text", "output_text"):
|
||||
parts.append(str(text))
|
||||
continue
|
||||
ptype = part.get("type")
|
||||
if ptype in (None, "text", "output_text"):
|
||||
t = part.get("text")
|
||||
if t:
|
||||
parts.append(str(t))
|
||||
return "".join(parts)
|
||||
return ""
|
||||
@@ -0,0 +1,78 @@
|
||||
"""从 Server 内部接口拉取 LLM 运行时配置。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
from config.settings import Settings
|
||||
from domain.models import LlmRuntimeConfig
|
||||
from domain.ports import LlmRuntimeGateway
|
||||
from infrastructure.llm.api_style import normalize_api_style
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
||||
"""GET /api/internal/agent/llm-runtime?companyId=&providerId=&model=。"""
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
self._settings = settings
|
||||
|
||||
async def fetch(
|
||||
self,
|
||||
company_id: int,
|
||||
provider_id: int | None = None,
|
||||
model: str | None = None,
|
||||
) -> LlmRuntimeConfig | None:
|
||||
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
|
||||
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
|
||||
params: dict[str, str | int] = {"companyId": company_id}
|
||||
if provider_id is not None:
|
||||
params["providerId"] = provider_id
|
||||
if model:
|
||||
params["model"] = model
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
resp = await client.get(url, params=params, headers=headers)
|
||||
if resp.status_code == 400:
|
||||
return None
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
data = body.get("data") if isinstance(body, dict) else None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
pid = data.get("providerId")
|
||||
return LlmRuntimeConfig(
|
||||
base_url=str(data.get("baseUrl") or "").rstrip("/"),
|
||||
api_key=str(data.get("apiKey") or ""),
|
||||
model=str(data.get("model") or ""),
|
||||
provider_id=int(pid) if pid is not None else provider_id,
|
||||
extra_headers={
|
||||
str(k): str(v)
|
||||
for k, v in (data.get("extraHeaders") or {}).items()
|
||||
},
|
||||
context_window=_optional_positive_int(data.get("contextWindow")),
|
||||
api_style=normalize_api_style(
|
||||
None if data.get("apiStyle") is None else str(data.get("apiStyle"))
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"拉取 Server LLM runtime 失败 company_id=%s provider_id=%s model=%s",
|
||||
company_id,
|
||||
provider_id,
|
||||
model,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _optional_positive_int(v) -> int | None:
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
n = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return n if n > 0 else None
|
||||
@@ -0,0 +1,45 @@
|
||||
"""MCP 工具加载(按请求注入公司/用户头)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from config.settings import Settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def load_mcp_tools(
|
||||
settings: Settings, *, company_id: int, user_id: str
|
||||
) -> list[Any]:
|
||||
if not settings.mcp_tools_enabled or not settings.mcp_bearer_token:
|
||||
return []
|
||||
try:
|
||||
from langchain_mcp_adapters.client import MultiServerMCPClient
|
||||
except ImportError:
|
||||
logger.warning("未安装 langchain-mcp-adapters,跳过 MCP tools")
|
||||
return []
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {settings.mcp_bearer_token}",
|
||||
"X-Agent-Company-Id": str(company_id),
|
||||
"X-Agent-User-Id": str(user_id),
|
||||
}
|
||||
try:
|
||||
client = MultiServerMCPClient(
|
||||
{
|
||||
"ecom-dmb": {
|
||||
"url": settings.mcp_base_url,
|
||||
"transport": "streamable_http",
|
||||
"headers": headers,
|
||||
}
|
||||
}
|
||||
)
|
||||
tools = await client.get_tools()
|
||||
return list(tools or [])
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"加载 MCP tools 失败 company_id=%s(将降级为无工具对话)", company_id
|
||||
)
|
||||
return []
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Mongo 连接与索引。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
|
||||
|
||||
from config.settings import Settings
|
||||
|
||||
_client: AsyncIOMotorClient | None = None
|
||||
|
||||
|
||||
async def get_db(settings: Settings) -> AsyncIOMotorDatabase:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = AsyncIOMotorClient(settings.mongo_uri)
|
||||
return _client[settings.mongo_db]
|
||||
|
||||
|
||||
async def ensure_indexes(db: AsyncIOMotorDatabase) -> None:
|
||||
await db.agent_sessions.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("thread_id", 1)], unique=True
|
||||
)
|
||||
await db.agent_sessions.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("status", 1), ("scene", 1), ("updated_at", -1)]
|
||||
)
|
||||
await db.agent_sessions.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("scene", 1), ("scene_ref", 1), ("status", 1)]
|
||||
)
|
||||
await db.agent_messages.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("thread_id", 1), ("seq", 1)]
|
||||
)
|
||||
await db.agent_user_memory.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("status", 1), ("kind", 1), ("updated_at", -1)]
|
||||
)
|
||||
await db.agent_user_memory.create_index(
|
||||
[("company_id", 1), ("user_id", 1), ("key", 1)],
|
||||
unique=True,
|
||||
partialFilterExpression={"key": {"$type": "string"}},
|
||||
)
|
||||
|
||||
|
||||
async def close_mongo() -> None:
|
||||
global _client
|
||||
if _client is not None:
|
||||
_client.close()
|
||||
_client = None
|
||||
@@ -0,0 +1,449 @@
|
||||
"""会话 / 消息 / 用户记忆 Mongo 实现。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
import re
|
||||
|
||||
from bson import ObjectId
|
||||
from motor.motor_asyncio import AsyncIOMotorDatabase
|
||||
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
LlmResponseChain,
|
||||
MemoryKind,
|
||||
MemoryStatus,
|
||||
MessageRole,
|
||||
Session,
|
||||
SessionStatus,
|
||||
UserMemory,
|
||||
)
|
||||
from domain.ports import MemoryRepository, MessageRepository, SessionRepository
|
||||
|
||||
|
||||
def _dt(v: Any) -> datetime:
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def _optional_int(v: Any) -> int | None:
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _chain_to_doc(chain: LlmResponseChain | None) -> dict[str, Any] | None:
|
||||
if chain is None or not (chain.previous_response_id or "").strip():
|
||||
return None
|
||||
return {
|
||||
"provider_id": chain.provider_id,
|
||||
"model": chain.model,
|
||||
"previous_response_id": chain.previous_response_id.strip(),
|
||||
}
|
||||
|
||||
|
||||
def _chain_from_doc(raw: Any) -> LlmResponseChain | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
rid = str(raw.get("previous_response_id") or "").strip()
|
||||
model = str(raw.get("model") or "").strip()
|
||||
if not rid or not model:
|
||||
return None
|
||||
return LlmResponseChain(
|
||||
provider_id=_optional_int(raw.get("provider_id")),
|
||||
model=model,
|
||||
previous_response_id=rid,
|
||||
)
|
||||
|
||||
|
||||
class MongoSessionRepository(SessionRepository):
|
||||
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
||||
self._col = db.agent_sessions
|
||||
|
||||
async def create(self, session: Session) -> Session:
|
||||
doc = {
|
||||
"thread_id": session.thread_id,
|
||||
"company_id": session.company_id,
|
||||
"user_id": session.user_id,
|
||||
"title": session.title,
|
||||
"status": session.status.value,
|
||||
"summary": session.summary,
|
||||
"scene": session.scene or "general",
|
||||
"scene_ref": session.scene_ref,
|
||||
"llm_provider_id": session.llm_provider_id,
|
||||
"llm_model": session.llm_model,
|
||||
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||
"created_at": session.created_at,
|
||||
"updated_at": session.updated_at,
|
||||
"last_message_at": session.last_message_at,
|
||||
}
|
||||
await self._col.insert_one(doc)
|
||||
return session
|
||||
|
||||
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None:
|
||||
doc = await self._col.find_one(
|
||||
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
|
||||
)
|
||||
return None if doc is None else self._to_session(doc)
|
||||
|
||||
async def list_active(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
limit: int = 50,
|
||||
*,
|
||||
scene: str | None = None,
|
||||
) -> list[Session]:
|
||||
query: dict[str, Any] = {
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": SessionStatus.ACTIVE.value,
|
||||
}
|
||||
# 缺省只列经营助手;旧文档无 scene 字段视为 general
|
||||
want = (scene or "general").strip() or "general"
|
||||
if want == "general":
|
||||
query["$or"] = [
|
||||
{"scene": "general"},
|
||||
{"scene": {"$exists": False}},
|
||||
{"scene": None},
|
||||
]
|
||||
else:
|
||||
query["scene"] = want
|
||||
cursor = (
|
||||
self._col.find(query)
|
||||
.sort("updated_at", -1)
|
||||
.limit(limit)
|
||||
)
|
||||
return [self._to_session(d) async for d in cursor]
|
||||
|
||||
async def find_active_by_scene_ref(
|
||||
self,
|
||||
company_id: int,
|
||||
user_id: str,
|
||||
*,
|
||||
scene: str,
|
||||
scene_ref: str,
|
||||
) -> Session | None:
|
||||
ref = (scene_ref or "").strip()
|
||||
if not ref:
|
||||
return None
|
||||
doc = await self._col.find_one(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": SessionStatus.ACTIVE.value,
|
||||
"scene": (scene or "").strip() or "general",
|
||||
"scene_ref": ref,
|
||||
},
|
||||
sort=[("updated_at", -1)],
|
||||
)
|
||||
return self._to_session(doc) if doc else None
|
||||
|
||||
async def update(self, session: Session) -> Session:
|
||||
session.updated_at = datetime.utcnow()
|
||||
await self._col.update_one(
|
||||
{
|
||||
"company_id": session.company_id,
|
||||
"user_id": session.user_id,
|
||||
"thread_id": session.thread_id,
|
||||
},
|
||||
{
|
||||
"$set": {
|
||||
"title": session.title,
|
||||
"status": session.status.value,
|
||||
"summary": session.summary,
|
||||
"scene": session.scene or "general",
|
||||
"scene_ref": session.scene_ref,
|
||||
"llm_provider_id": session.llm_provider_id,
|
||||
"llm_model": session.llm_model,
|
||||
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||
"updated_at": session.updated_at,
|
||||
"last_message_at": session.last_message_at,
|
||||
}
|
||||
},
|
||||
)
|
||||
return session
|
||||
|
||||
@staticmethod
|
||||
def _to_session(doc: dict[str, Any]) -> Session:
|
||||
return Session(
|
||||
thread_id=doc["thread_id"],
|
||||
company_id=int(doc["company_id"]),
|
||||
user_id=str(doc["user_id"]),
|
||||
title=doc.get("title") or "新对话",
|
||||
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
|
||||
summary=doc.get("summary"),
|
||||
scene=(doc.get("scene") or "general"),
|
||||
scene_ref=doc.get("scene_ref"),
|
||||
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
||||
llm_model=doc.get("llm_model"),
|
||||
llm_response_chain=_chain_from_doc(doc.get("llm_response_chain")),
|
||||
created_at=_dt(doc.get("created_at")),
|
||||
updated_at=_dt(doc.get("updated_at")),
|
||||
last_message_at=doc.get("last_message_at"),
|
||||
)
|
||||
|
||||
|
||||
class MongoMessageRepository(MessageRepository):
|
||||
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
||||
self._col = db.agent_messages
|
||||
|
||||
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int:
|
||||
doc = await self._col.find_one(
|
||||
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id},
|
||||
sort=[("seq", -1)],
|
||||
projection={"seq": 1},
|
||||
)
|
||||
return 1 if doc is None else int(doc["seq"]) + 1
|
||||
|
||||
async def append(self, message: ChatMessage) -> ChatMessage:
|
||||
doc = {
|
||||
"company_id": message.company_id,
|
||||
"user_id": message.user_id,
|
||||
"thread_id": message.thread_id,
|
||||
"seq": message.seq,
|
||||
"role": message.role.value,
|
||||
"content": message.content,
|
||||
"tool_name": message.tool_name,
|
||||
"tool_call_id": message.tool_call_id,
|
||||
"created_at": message.created_at,
|
||||
}
|
||||
result = await self._col.insert_one(doc)
|
||||
message.id = str(result.inserted_id)
|
||||
return message
|
||||
|
||||
async def list_recent(
|
||||
self, company_id: int, user_id: str, thread_id: str, limit: int
|
||||
) -> list[ChatMessage]:
|
||||
cursor = (
|
||||
self._col.find(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"thread_id": thread_id,
|
||||
# 兼容旧文档无 status;软删后 status=deleted
|
||||
"$or": [
|
||||
{"status": {"$exists": False}},
|
||||
{"status": None},
|
||||
{"status": {"$ne": "deleted"}},
|
||||
],
|
||||
}
|
||||
)
|
||||
.sort("seq", -1)
|
||||
.limit(limit)
|
||||
)
|
||||
rows = [self._to_msg(d) async for d in cursor]
|
||||
rows.reverse()
|
||||
return rows
|
||||
|
||||
async def soft_delete_by_thread(
|
||||
self, company_id: int, user_id: str, thread_id: str
|
||||
) -> int:
|
||||
result = await self._col.update_many(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"thread_id": thread_id,
|
||||
"$or": [
|
||||
{"status": {"$exists": False}},
|
||||
{"status": None},
|
||||
{"status": {"$ne": "deleted"}},
|
||||
],
|
||||
},
|
||||
{"$set": {"status": "deleted", "deleted_at": datetime.utcnow()}},
|
||||
)
|
||||
return int(result.modified_count or 0)
|
||||
|
||||
@staticmethod
|
||||
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
|
||||
return ChatMessage(
|
||||
id=str(doc.get("_id")),
|
||||
company_id=int(doc["company_id"]),
|
||||
user_id=str(doc["user_id"]),
|
||||
thread_id=doc["thread_id"],
|
||||
seq=int(doc["seq"]),
|
||||
role=MessageRole(doc["role"]),
|
||||
content=doc.get("content") or "",
|
||||
tool_name=doc.get("tool_name"),
|
||||
tool_call_id=doc.get("tool_call_id"),
|
||||
created_at=_dt(doc.get("created_at")),
|
||||
)
|
||||
|
||||
|
||||
class MongoMemoryRepository(MemoryRepository):
|
||||
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
||||
self._col = db.agent_user_memory
|
||||
|
||||
async def list_active(
|
||||
self, company_id: int, user_id: str, limit: int
|
||||
) -> list[UserMemory]:
|
||||
cursor = (
|
||||
self._col.find(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": MemoryStatus.ACTIVE.value,
|
||||
}
|
||||
)
|
||||
.sort("updated_at", -1)
|
||||
.limit(limit)
|
||||
)
|
||||
return [self._to_mem(d) async for d in cursor]
|
||||
|
||||
async def count_active(self, company_id: int, user_id: str) -> int:
|
||||
return int(
|
||||
await self._col.count_documents(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": MemoryStatus.ACTIVE.value,
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
async def search(
|
||||
self, company_id: int, user_id: str, query: str, limit: int
|
||||
) -> list[UserMemory]:
|
||||
"""按摘要/正文关键词匹配(非向量);无关键词时退化为最近更新列表。"""
|
||||
tokens = _keyword_tokens(query)
|
||||
filt: dict[str, Any] = {
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": MemoryStatus.ACTIVE.value,
|
||||
}
|
||||
if tokens:
|
||||
token_clauses = []
|
||||
for t in tokens:
|
||||
escaped = re.escape(t)
|
||||
token_clauses.append(
|
||||
{
|
||||
"$or": [
|
||||
{"summary": {"$regex": escaped, "$options": "i"}},
|
||||
{"text": {"$regex": escaped, "$options": "i"}},
|
||||
]
|
||||
}
|
||||
)
|
||||
filt["$and"] = token_clauses
|
||||
cursor = self._col.find(filt).sort("updated_at", -1).limit(max(1, min(limit, 20)))
|
||||
return [self._to_mem(d) async for d in cursor]
|
||||
|
||||
async def get_by_ids(
|
||||
self, company_id: int, user_id: str, memory_ids: list[str]
|
||||
) -> list[UserMemory]:
|
||||
oids: list[ObjectId] = []
|
||||
for mid in memory_ids:
|
||||
try:
|
||||
oids.append(ObjectId(mid))
|
||||
except Exception:
|
||||
continue
|
||||
if not oids:
|
||||
return []
|
||||
cursor = self._col.find(
|
||||
{
|
||||
"_id": {"$in": oids},
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"status": MemoryStatus.ACTIVE.value,
|
||||
}
|
||||
)
|
||||
by_id: dict[str, UserMemory] = {}
|
||||
async for d in cursor:
|
||||
by_id[str(d["_id"])] = self._to_mem(d)
|
||||
# 保持调用方 id 顺序
|
||||
return [by_id[mid] for mid in memory_ids if mid in by_id]
|
||||
|
||||
async def upsert(self, memory: UserMemory) -> UserMemory:
|
||||
memory.updated_at = datetime.utcnow()
|
||||
if not (memory.summary or "").strip():
|
||||
memory.summary = _fallback_summary(memory.text)
|
||||
payload = {
|
||||
"company_id": memory.company_id,
|
||||
"user_id": memory.user_id,
|
||||
"kind": memory.kind.value,
|
||||
"key": memory.key,
|
||||
"text": memory.text,
|
||||
"summary": memory.summary,
|
||||
"value": memory.value,
|
||||
"source_thread_id": memory.source_thread_id,
|
||||
"status": memory.status.value,
|
||||
"confidence": memory.confidence,
|
||||
"updated_at": memory.updated_at,
|
||||
}
|
||||
if memory.key:
|
||||
existing = await self._col.find_one(
|
||||
{
|
||||
"company_id": memory.company_id,
|
||||
"user_id": memory.user_id,
|
||||
"key": memory.key,
|
||||
"status": {"$ne": MemoryStatus.DELETED.value},
|
||||
}
|
||||
)
|
||||
if existing:
|
||||
await self._col.update_one({"_id": existing["_id"]}, {"$set": payload})
|
||||
memory.id = str(existing["_id"])
|
||||
memory.created_at = _dt(existing.get("created_at"))
|
||||
return memory
|
||||
|
||||
payload["created_at"] = memory.created_at
|
||||
result = await self._col.insert_one(payload)
|
||||
memory.id = str(result.inserted_id)
|
||||
return memory
|
||||
|
||||
async def soft_delete(self, company_id: int, user_id: str, memory_id: str) -> bool:
|
||||
try:
|
||||
oid = ObjectId(memory_id)
|
||||
except Exception:
|
||||
return False
|
||||
result = await self._col.update_one(
|
||||
{"_id": oid, "company_id": company_id, "user_id": user_id},
|
||||
{
|
||||
"$set": {
|
||||
"status": MemoryStatus.DELETED.value,
|
||||
"updated_at": datetime.utcnow(),
|
||||
}
|
||||
},
|
||||
)
|
||||
return result.modified_count > 0
|
||||
|
||||
@staticmethod
|
||||
def _to_mem(doc: dict[str, Any]) -> UserMemory:
|
||||
text = doc.get("text") or ""
|
||||
summary = (doc.get("summary") or "").strip() or _fallback_summary(text)
|
||||
return UserMemory(
|
||||
id=str(doc.get("_id")),
|
||||
company_id=int(doc["company_id"]),
|
||||
user_id=str(doc["user_id"]),
|
||||
kind=MemoryKind(doc.get("kind") or MemoryKind.FACT.value),
|
||||
key=doc.get("key"),
|
||||
text=text,
|
||||
summary=summary,
|
||||
value=doc.get("value") or {},
|
||||
source_thread_id=doc.get("source_thread_id"),
|
||||
status=MemoryStatus(doc.get("status") or MemoryStatus.ACTIVE.value),
|
||||
confidence=float(doc.get("confidence") or 0.8),
|
||||
created_at=_dt(doc.get("created_at")),
|
||||
updated_at=_dt(doc.get("updated_at")),
|
||||
)
|
||||
|
||||
|
||||
def _fallback_summary(text: str, max_len: int = 80) -> str:
|
||||
s = (text or "").strip().replace("\n", " ")
|
||||
if len(s) <= max_len:
|
||||
return s
|
||||
return s[: max_len - 1] + "…"
|
||||
|
||||
|
||||
def _keyword_tokens(query: str) -> list[str]:
|
||||
"""按空白与常见标点切词;过短 token 丢弃。"""
|
||||
parts = re.split(r"[\s,,。.!!??;;::、/\\|]+", (query or "").strip())
|
||||
out: list[str] = []
|
||||
for p in parts:
|
||||
t = p.strip()
|
||||
if len(t) >= 1 and t not in out:
|
||||
out.append(t)
|
||||
return out[:8]
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Redis 缓存租户 LLM 运行时配置(按公司+提供商+模型)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import redis.asyncio as redis
|
||||
|
||||
from config.settings import Settings
|
||||
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
|
||||
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
|
||||
from infrastructure.llm.api_style import normalize_api_style
|
||||
|
||||
|
||||
class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
def __init__(self, client: redis.Redis) -> None:
|
||||
self._r = client
|
||||
|
||||
@staticmethod
|
||||
def _key(company_id: int, provider_id: int | None, model: str | None) -> str:
|
||||
if provider_id is not None and model:
|
||||
return f"agent:llm:rt:{company_id}:{provider_id}:{model}"
|
||||
if model:
|
||||
return f"agent:llm:rt:{company_id}:{model}"
|
||||
return f"agent:llm:rt:{company_id}"
|
||||
|
||||
async def get(
|
||||
self,
|
||||
company_id: int,
|
||||
provider_id: int | None = None,
|
||||
model: str | None = None,
|
||||
) -> LlmRuntimeConfig | None:
|
||||
raw = await self._r.get(self._key(company_id, provider_id, model))
|
||||
if not raw and provider_id is not None and model:
|
||||
# 兼容旧键 companyId:model
|
||||
raw = await self._r.get(self._key(company_id, None, model))
|
||||
if not raw:
|
||||
return None
|
||||
data = json.loads(raw)
|
||||
cfg = LlmRuntimeConfig(
|
||||
base_url=data["base_url"],
|
||||
api_key=data["api_key"],
|
||||
model=data["model"],
|
||||
provider_id=_optional_int(data.get("provider_id")) or provider_id,
|
||||
extra_headers=data.get("extra_headers") or {},
|
||||
context_window=_optional_int(data.get("context_window")),
|
||||
api_style=normalize_api_style(data.get("api_style")),
|
||||
)
|
||||
if model and cfg.model and cfg.model != model:
|
||||
return None
|
||||
if provider_id is not None and cfg.provider_id is not None and cfg.provider_id != provider_id:
|
||||
return None
|
||||
return cfg
|
||||
|
||||
async def set(
|
||||
self,
|
||||
company_id: int,
|
||||
config: LlmRuntimeConfig,
|
||||
ttl_seconds: int,
|
||||
) -> None:
|
||||
payload = {
|
||||
"provider_id": config.provider_id,
|
||||
"base_url": config.base_url,
|
||||
"api_key": config.api_key,
|
||||
"model": config.model,
|
||||
"extra_headers": config.extra_headers,
|
||||
"context_window": config.context_window,
|
||||
"api_style": normalize_api_style(config.api_style),
|
||||
}
|
||||
await self._r.set(
|
||||
self._key(company_id, config.provider_id, config.model),
|
||||
json.dumps(payload),
|
||||
ex=ttl_seconds,
|
||||
)
|
||||
|
||||
async def delete(self, company_id: int) -> None:
|
||||
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
|
||||
if keys:
|
||||
await self._r.delete(*keys)
|
||||
|
||||
|
||||
_redis: redis.Redis | None = None
|
||||
|
||||
|
||||
def _optional_int(v) -> int | None:
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
n = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return n if n > 0 else None
|
||||
|
||||
|
||||
def get_redis(settings: Settings) -> redis.Redis:
|
||||
global _redis
|
||||
if _redis is None:
|
||||
_redis = redis.from_url(settings.redis_url, decode_responses=True)
|
||||
return _redis
|
||||
|
||||
|
||||
class RedisLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
|
||||
"""按 provider_id(优先)或 base_url 缓存 Responses/store 能力。"""
|
||||
|
||||
def __init__(self, client: redis.Redis) -> None:
|
||||
self._r = client
|
||||
|
||||
@staticmethod
|
||||
def _key(*, provider_id: int | None, base_url: str) -> str:
|
||||
if provider_id is not None and int(provider_id) > 0:
|
||||
return f"agent:llm:cap:p:{int(provider_id)}"
|
||||
url = (base_url or "").rstrip("/").lower()
|
||||
return f"agent:llm:cap:u:{url}"
|
||||
|
||||
async def get(
|
||||
self, *, provider_id: int | None, base_url: str
|
||||
) -> LlmProtocolCapability | None:
|
||||
raw = await self._r.get(self._key(provider_id=provider_id, base_url=base_url))
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return LlmProtocolCapability(
|
||||
responses=data.get("responses"),
|
||||
store=data.get("store"),
|
||||
)
|
||||
|
||||
async def set(
|
||||
self,
|
||||
*,
|
||||
provider_id: int | None,
|
||||
base_url: str,
|
||||
capability: LlmProtocolCapability,
|
||||
ttl_seconds: int,
|
||||
) -> None:
|
||||
payload = {
|
||||
"responses": capability.responses,
|
||||
"store": capability.store,
|
||||
}
|
||||
await self._r.set(
|
||||
self._key(provider_id=provider_id, base_url=base_url),
|
||||
json.dumps(payload),
|
||||
ex=max(60, ttl_seconds),
|
||||
)
|
||||
|
||||
|
||||
async def close_redis() -> None:
|
||||
global _redis
|
||||
if _redis is not None:
|
||||
await _redis.aclose()
|
||||
_redis = None
|
||||
Reference in New Issue
Block a user