mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 05:09:19 +08:00
Compare commits
5
Commits
master
...
0b460e22b0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b460e22b0 | ||
|
|
41f022bd63 | ||
|
|
71eca63461 | ||
|
|
d20c6a1302 | ||
|
|
9c2c1ed061 |
+21
-1
@@ -125,6 +125,7 @@ apps/agent/
|
||||
| `summary` | 会话滚动摘要(可选) |
|
||||
| `llm_provider_id` | 会话选用的提供商 id |
|
||||
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
|
||||
| `llm_response_chain` | 可选;Responses 续链 `{provider_id,model,previous_response_id}` |
|
||||
| `created_at`, `updated_at`, `last_message_at` | |
|
||||
|
||||
唯一索引:`(company_id, user_id, thread_id)`
|
||||
@@ -363,6 +364,25 @@ apps/agent/
|
||||
|
||||
---
|
||||
|
||||
## 11. 文档维护
|
||||
## 11. Responses API 分期(多提供商)
|
||||
|
||||
原则:**Mongo 仍是对话真相源**;Responses 链(`previous_response_id`)只是同提供商同模型下的加速缓存,切换选型即作废并全量 rebuild。
|
||||
|
||||
### Responses-P0 / P1(已落地)— 运行时探测,不写死主机
|
||||
|
||||
原则:优先新协议;能力靠探测 + Redis 缓存(`agent:llm:cap:*`),按错误回退,不按 OpenAI/DeepSeek 主机写死。
|
||||
|
||||
同轮未产出 token 前的阶梯:
|
||||
|
||||
1. **Responses + `store=true`**(语义证实后;有会话链则只发增量 + `previous_response_id`)
|
||||
2. store 未知:Responses + `store=true` + **Mongo 全量历史**,成功后再做语义探测
|
||||
3. **store 证伪**:先 **无状态 Responses + Mongo 全量**,接口失败再 **Completions + Mongo 全量**
|
||||
4. Responses 端点不可用 → Completions
|
||||
|
||||
成功后写入能力缓存。**`store=true` 认定**:独立语义探测——先让模型记住密钥,再仅用 `previous_response_id`(不带历史)追问;答对才记 true。未证实前禁止只发增量。
|
||||
|
||||
---
|
||||
|
||||
## 12. 文档维护
|
||||
|
||||
落地后同步:根目录 `AGENTS.md` 增加 `apps/agent`;`apps/server/docs/Agent与MCP接入及Boot升级说明.md` 勾选 LangGraph 项并注明多租户 MCP 与租户 LLM Key 约定。
|
||||
|
||||
@@ -16,7 +16,7 @@ uvicorn api.main:app --reload --host 0.0.0.0 --port 8200
|
||||
健康检查:`GET http://localhost:8200/health`
|
||||
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
|
||||
|
||||
**模型 API 配置不在本服务**:浏览器走 Java `GET/PUT /api/company/agent-llm-settings`(凭证 + 多模型勾选;`POST .../probe-models` 拉目录);Agent 经 Redis `agent:llm:rt:{companyId}` 或内部接口拉**默认模型**明文注入。
|
||||
**模型 API 配置不在本服务**:浏览器走 Java 提供商 CRUD(含 `apiStyle`);Agent 拉 runtime 后**运行时探测** Responses/store,结果缓存 Redis `agent:llm:cap:*`,失败阶梯为 Responses+store → Responses → Completions(见 DESIGN §11)。
|
||||
|
||||
## 分环境配置
|
||||
|
||||
|
||||
@@ -19,7 +19,11 @@ from infrastructure.persistence.mongo.repositories import (
|
||||
MongoMessageRepository,
|
||||
MongoSessionRepository,
|
||||
)
|
||||
from infrastructure.persistence.redis.cache import RedisLlmRuntimeCache, get_redis
|
||||
from infrastructure.persistence.redis.cache import (
|
||||
RedisLlmProtocolCapabilityCache,
|
||||
RedisLlmRuntimeCache,
|
||||
get_redis,
|
||||
)
|
||||
|
||||
|
||||
async def current_actor(
|
||||
@@ -68,5 +72,8 @@ async def chat_service(
|
||||
messages=MongoMessageRepository(db),
|
||||
llm_runtime=llm_svc,
|
||||
memory=mem_svc,
|
||||
streamer=OpenAICompatibleStreamer(),
|
||||
streamer=OpenAICompatibleStreamer(
|
||||
RedisLlmProtocolCapabilityCache(get_redis(settings)),
|
||||
capability_ttl_seconds=settings.llm_capability_ttl_seconds,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -12,7 +12,13 @@ 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, MessageRole, StreamEvent
|
||||
from domain.models import (
|
||||
Actor,
|
||||
ChatMessage,
|
||||
LlmResponseChain,
|
||||
MessageRole,
|
||||
StreamEvent,
|
||||
)
|
||||
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
|
||||
|
||||
|
||||
@@ -63,7 +69,6 @@ class ChatService:
|
||||
provider_id=session.llm_provider_id,
|
||||
model=session.llm_model,
|
||||
)
|
||||
# 回落默认或消歧后写回会话,保证列表/选框稳定
|
||||
changed = False
|
||||
if session.llm_model != llm.model:
|
||||
session.llm_model = llm.model
|
||||
@@ -72,6 +77,13 @@ class ChatService:
|
||||
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
|
||||
@@ -120,7 +132,6 @@ class ChatService:
|
||||
reserve_output_tokens=self._settings.context_reserve_output_tokens,
|
||||
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
|
||||
)
|
||||
# 本轮 tool 结果字符上限(与预留 tool token 粗对齐)
|
||||
max_tool_chars = max(
|
||||
500, self._settings.context_reserve_tool_tokens * 2
|
||||
)
|
||||
@@ -142,6 +153,7 @@ class ChatService:
|
||||
await self._session_repo.update(session)
|
||||
|
||||
parts: list[str] = []
|
||||
new_response_id: str | None = None
|
||||
async for event in self._streamer.stream_reply(
|
||||
llm=llm,
|
||||
history=history,
|
||||
@@ -149,7 +161,11 @@ class ChatService:
|
||||
system_prompt=system_prompt,
|
||||
tools=tools or None,
|
||||
max_tool_result_chars=max_tool_chars,
|
||||
previous_response_id=chain_id,
|
||||
):
|
||||
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
|
||||
@@ -167,4 +183,26 @@ class ChatService:
|
||||
)
|
||||
)
|
||||
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
|
||||
|
||||
@@ -53,6 +53,7 @@ class LlmRuntimeService:
|
||||
model=self._settings.llm_fallback_model,
|
||||
provider_id=None,
|
||||
context_window=None,
|
||||
api_style="auto",
|
||||
)
|
||||
|
||||
raise HTTPException(
|
||||
|
||||
@@ -103,8 +103,15 @@ class SessionService:
|
||||
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:
|
||||
|
||||
@@ -12,9 +12,10 @@ _BASE_SYSTEM = (
|
||||
"需要经营数据时优先调用可用工具。"
|
||||
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
|
||||
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
|
||||
"你具备跨会话的用户级长期记忆,但内容不会自动注入对话。"
|
||||
"需要称呼、偏好或用户事实时:先 memory_search,必要时再 memory_load;"
|
||||
"禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
||||
"【本会话上下文】请求里已包含本会话近期的用户与助手原文,你可以直接看见并引用;"
|
||||
"禁止声称「只收到当前一句」或「前面几轮不会带过来」——那是错误描述。"
|
||||
"【长期记忆】跨会话的用户级记忆不会自动注入;需要称呼、偏好或用户事实时:"
|
||||
"先 memory_search,必要时再 memory_load;禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
||||
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
|
||||
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
|
||||
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
|
||||
|
||||
@@ -77,6 +77,8 @@ class Settings(BaseSettings):
|
||||
# 为模型输出与本轮 tool 预留的 token
|
||||
context_reserve_output_tokens: int = 4096
|
||||
context_reserve_tool_tokens: int = 8192
|
||||
# Responses/store 能力缓存 TTL(秒)
|
||||
llm_capability_ttl_seconds: int = 604800
|
||||
|
||||
@property
|
||||
def cors_origin_list(self) -> list[str]:
|
||||
|
||||
@@ -50,6 +50,15 @@ class Actor:
|
||||
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
|
||||
@@ -65,6 +74,8 @@ class Session:
|
||||
# 会话选用的提供商 + 模型(同名 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
|
||||
@@ -118,19 +129,31 @@ class LlmRuntimeConfig:
|
||||
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
|
||||
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:
|
||||
@@ -159,3 +182,8 @@ class StreamEvent:
|
||||
@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)
|
||||
|
||||
@@ -5,7 +5,14 @@ from __future__ import annotations
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from domain.models import ChatMessage, LlmRuntimeConfig, Session, StreamEvent, UserMemory
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
LlmProtocolCapability,
|
||||
LlmRuntimeConfig,
|
||||
Session,
|
||||
StreamEvent,
|
||||
UserMemory,
|
||||
)
|
||||
|
||||
|
||||
class SessionRepository(ABC):
|
||||
@@ -111,6 +118,25 @@ class LlmRuntimeGateway(ABC):
|
||||
) -> 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 ChatStreamer(ABC):
|
||||
"""流式生成助手回复。"""
|
||||
|
||||
@@ -124,4 +150,5 @@ class ChatStreamer(ABC):
|
||||
system_prompt: str,
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 4000,
|
||||
previous_response_id: str | None = None,
|
||||
) -> AsyncIterator[StreamEvent]: ...
|
||||
|
||||
@@ -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"
|
||||
@@ -1,8 +1,13 @@
|
||||
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。"""
|
||||
"""按租户构建 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
|
||||
@@ -10,11 +15,36 @@ 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, LlmRuntimeConfig, MessageRole, StreamEvent
|
||||
from domain.ports import ChatStreamer
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
LlmProtocolCapability,
|
||||
LlmRuntimeConfig,
|
||||
MessageRole,
|
||||
StreamEvent,
|
||||
)
|
||||
from domain.ports import ChatStreamer, 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,
|
||||
*,
|
||||
@@ -24,40 +54,331 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
system_prompt: str,
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 8000,
|
||||
previous_response_id: str | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
model = ChatOpenAI(
|
||||
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,
|
||||
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)
|
||||
)
|
||||
messages: list[Any] = [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))
|
||||
|
||||
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,
|
||||
):
|
||||
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,
|
||||
) -> 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):
|
||||
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
|
||||
|
||||
# 工具轮:每轮用 astream 边生成边推 token;出现 tool_call 再执行工具后继续
|
||||
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 _ in range(5):
|
||||
for round_idx in range(5):
|
||||
gathered = None
|
||||
saw_tool = False
|
||||
async for chunk in bound.astream(messages):
|
||||
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):
|
||||
if getattr(chunk, "tool_call_chunks", None) or getattr(
|
||||
chunk, "tool_calls", None
|
||||
):
|
||||
saw_tool = True
|
||||
continue
|
||||
if saw_tool:
|
||||
@@ -65,12 +386,19 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
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()
|
||||
@@ -121,19 +449,44 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
)
|
||||
|
||||
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, dict) and part.get("type") == "text":
|
||||
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))
|
||||
elif isinstance(part, str):
|
||||
parts.append(part)
|
||||
return "".join(parts)
|
||||
return ""
|
||||
|
||||
@@ -9,6 +9,7 @@ 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__)
|
||||
|
||||
@@ -53,6 +54,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
||||
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(
|
||||
|
||||
@@ -11,6 +11,7 @@ from motor.motor_asyncio import AsyncIOMotorDatabase
|
||||
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
LlmResponseChain,
|
||||
MemoryKind,
|
||||
MemoryStatus,
|
||||
MessageRole,
|
||||
@@ -36,6 +37,30 @@ def _optional_int(v: Any) -> int | None:
|
||||
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
|
||||
@@ -52,6 +77,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
"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,
|
||||
@@ -135,6 +161,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
"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,
|
||||
}
|
||||
@@ -155,6 +182,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
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"),
|
||||
|
||||
@@ -7,8 +7,9 @@ import json
|
||||
import redis.asyncio as redis
|
||||
|
||||
from config.settings import Settings
|
||||
from domain.models import LlmRuntimeConfig
|
||||
from domain.ports import LlmRuntimeCache
|
||||
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
|
||||
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
|
||||
from infrastructure.llm.api_style import normalize_api_style
|
||||
|
||||
|
||||
class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
@@ -43,6 +44,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
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
|
||||
@@ -63,6 +65,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
"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),
|
||||
@@ -96,6 +99,53 @@ def get_redis(settings: Settings) -> redis.Redis:
|
||||
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:
|
||||
|
||||
@@ -8,7 +8,7 @@ motor>=3.6.0
|
||||
redis>=5.2.0
|
||||
httpx>=0.27.0
|
||||
langchain-core>=0.3.0
|
||||
langchain-openai>=0.2.0
|
||||
langchain-openai>=0.3.26
|
||||
langchain-mcp-adapters>=0.1.0
|
||||
langgraph>=0.2.0
|
||||
sse-starlette>=2.1.0
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""协议探测规划与错误分类。"""
|
||||
|
||||
from domain.models import LlmProtocolCapability
|
||||
from infrastructure.llm.api_style import (
|
||||
ProtocolAttempt,
|
||||
classify_protocol_error,
|
||||
normalize_api_style,
|
||||
plan_protocol_attempts,
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_api_style():
|
||||
assert normalize_api_style(None) == "auto"
|
||||
assert normalize_api_style("Responses") == "responses"
|
||||
|
||||
|
||||
def test_plan_unknown_auto_tries_store_full_history_then_fallbacks():
|
||||
attempts = plan_protocol_attempts("auto", None, has_chain_id=True)
|
||||
assert attempts[0] == ProtocolAttempt(True, True, False)
|
||||
assert ProtocolAttempt(True, False, False) in attempts
|
||||
assert ProtocolAttempt(False, False, False) in attempts
|
||||
assert not any(a.use_chain for a in attempts)
|
||||
|
||||
|
||||
def test_plan_store_true_allows_chain():
|
||||
cap = LlmProtocolCapability(responses=True, store=True)
|
||||
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
|
||||
assert attempts[0] == ProtocolAttempt(True, True, True)
|
||||
assert ProtocolAttempt(True, True, False) in attempts
|
||||
|
||||
|
||||
def test_plan_store_false_prefers_stateless_responses_then_completions():
|
||||
"""store 证伪:无状态 Responses(全量历史)→ Completions。"""
|
||||
cap = LlmProtocolCapability(responses=True, store=False)
|
||||
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
|
||||
assert attempts == [
|
||||
ProtocolAttempt(True, False, False),
|
||||
ProtocolAttempt(False, False, False),
|
||||
]
|
||||
assert not any(a.use_chain or a.use_store for a in attempts)
|
||||
|
||||
|
||||
def test_plan_store_false_forced_responses_same_ladder():
|
||||
cap = LlmProtocolCapability(responses=True, store=False)
|
||||
attempts = plan_protocol_attempts("responses", cap, has_chain_id=False)
|
||||
assert attempts[0] == ProtocolAttempt(True, False, False)
|
||||
assert ProtocolAttempt(False, False, False) in attempts
|
||||
|
||||
|
||||
def test_plan_completions_only():
|
||||
assert plan_protocol_attempts("completions", None, has_chain_id=True) == [
|
||||
ProtocolAttempt(False, False, False)
|
||||
]
|
||||
|
||||
|
||||
def test_plan_responses_known_unsupported_falls_to_completions():
|
||||
cap = LlmProtocolCapability(responses=False, store=False)
|
||||
attempts = plan_protocol_attempts("auto", cap, has_chain_id=False)
|
||||
assert attempts == [ProtocolAttempt(False, False, False)]
|
||||
|
||||
|
||||
def test_classify_protocol_error():
|
||||
assert classify_protocol_error(Exception("Invalid previous_response_id")) == "chain"
|
||||
assert (
|
||||
classify_protocol_error(Exception("Unsupported parameter: store")) == "store"
|
||||
)
|
||||
assert classify_protocol_error(Exception("404 /v1/responses not found")) == "responses"
|
||||
assert classify_protocol_error(Exception("rate limit")) == "other"
|
||||
@@ -0,0 +1,32 @@
|
||||
"""会话链选型匹配。"""
|
||||
|
||||
from domain.models import LlmResponseChain, LlmRuntimeConfig
|
||||
from application.chat_service import _usable_chain_id
|
||||
|
||||
|
||||
def test_usable_chain_id_matches():
|
||||
llm = LlmRuntimeConfig(
|
||||
base_url="https://api.openai.com/v1",
|
||||
api_key="k",
|
||||
model="gpt-4o-mini",
|
||||
provider_id=3,
|
||||
api_style="auto",
|
||||
)
|
||||
chain = LlmResponseChain(
|
||||
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
|
||||
)
|
||||
assert _usable_chain_id(chain, llm) == "resp_abc"
|
||||
|
||||
|
||||
def test_usable_chain_id_clears_on_model_switch():
|
||||
llm = LlmRuntimeConfig(
|
||||
base_url="https://api.openai.com/v1",
|
||||
api_key="k",
|
||||
model="gpt-4o",
|
||||
provider_id=3,
|
||||
api_style="auto",
|
||||
)
|
||||
chain = LlmResponseChain(
|
||||
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
|
||||
)
|
||||
assert _usable_chain_id(chain, llm) is None
|
||||
@@ -16,6 +16,7 @@ CREATE TABLE IF NOT EXISTS `agent_company_llm_provider` (
|
||||
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
||||
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
||||
`display_name` varchar(100) NULL COMMENT '展示名,如 DeepSeek',
|
||||
`api_style` varchar(32) NOT NULL DEFAULT 'auto' COMMENT 'API协议:auto|completions|responses',
|
||||
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
||||
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
||||
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- 提供商增加 API 协议风格:auto | completions | responses
|
||||
ALTER TABLE `agent_company_llm_provider`
|
||||
ADD COLUMN `api_style` varchar(32) NOT NULL DEFAULT 'auto'
|
||||
COMMENT 'API协议:auto=按base_url推断;completions;responses'
|
||||
AFTER `display_name`;
|
||||
+5
@@ -16,4 +16,9 @@ public class CreateAgentLlmProviderDTO {
|
||||
private String apiKey;
|
||||
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses;空则 auto
|
||||
*/
|
||||
private String apiStyle;
|
||||
}
|
||||
|
||||
+5
@@ -16,4 +16,9 @@ public class UpdateAgentLlmProviderDTO {
|
||||
|
||||
/** 传 null 表示不改;传空串可清空备注 */
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses;null 不改
|
||||
*/
|
||||
private String apiStyle;
|
||||
}
|
||||
|
||||
+6
@@ -33,6 +33,12 @@ public class AgentCompanyLlmProviderPO {
|
||||
@TableField("display_name")
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
@TableField("api_style")
|
||||
private String apiStyle;
|
||||
|
||||
@TableField("extra_headers_json")
|
||||
private String extraHeadersJson;
|
||||
|
||||
|
||||
+4
@@ -16,5 +16,9 @@ public class AgentLlmProviderVO {
|
||||
private String displayName;
|
||||
private String apiKeyMasked;
|
||||
private String updateTime;
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
private String apiStyle;
|
||||
private List<AgentLlmModelVO> models = new ArrayList<>();
|
||||
}
|
||||
|
||||
+4
@@ -15,5 +15,9 @@ public class AgentLlmRuntimeVO {
|
||||
private String model;
|
||||
/** 上下文窗口 token;可能为 null */
|
||||
private Integer contextWindow;
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
private String apiStyle;
|
||||
private Map<String, String> extraHeaders;
|
||||
}
|
||||
|
||||
+20
@@ -98,6 +98,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
po.setApiKeyEncrypted(crypto.encrypt(plain));
|
||||
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
||||
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||
po.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
providerMapper.insert(po);
|
||||
@@ -123,6 +124,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
if (dto.getDisplayName() != null) {
|
||||
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||
}
|
||||
if (dto.getApiStyle() != null) {
|
||||
existing.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||
}
|
||||
existing.setUpdateBy(userId);
|
||||
providerMapper.updateById(existing);
|
||||
evictRuntimeCache(companyId);
|
||||
@@ -432,6 +436,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||
vo.setModel(model.getModel());
|
||||
vo.setContextWindow(model.getContextWindow());
|
||||
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
||||
return vo;
|
||||
}
|
||||
@@ -450,6 +455,17 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalizeApiStyle(String raw) {
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return "auto";
|
||||
}
|
||||
String s = raw.trim().toLowerCase();
|
||||
if ("auto".equals(s) || "completions".equals(s) || "responses".equals(s)) {
|
||||
return s;
|
||||
}
|
||||
throw new BusinessException("apiStyle 必须是 auto / completions / responses");
|
||||
}
|
||||
|
||||
private static Integer normalizeContextWindow(Integer raw) {
|
||||
if (raw == null || raw <= 0) {
|
||||
return null;
|
||||
@@ -546,6 +562,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
vo.setConfigured(true);
|
||||
vo.setBaseUrl(provider.getBaseUrl());
|
||||
vo.setDisplayName(provider.getDisplayName());
|
||||
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
||||
if (provider.getUpdateTime() != null) {
|
||||
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
||||
@@ -570,6 +587,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
payload.put("api_key", runtime.getApiKey());
|
||||
payload.put("model", runtime.getModel());
|
||||
payload.put("context_window", runtime.getContextWindow());
|
||||
payload.put("api_style", runtime.getApiStyle() == null ? "auto" : runtime.getApiStyle());
|
||||
payload.put("extra_headers",
|
||||
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||
stringRedisTemplate.opsForValue().set(
|
||||
@@ -612,6 +630,8 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
} else {
|
||||
vo.setContextWindow(null);
|
||||
}
|
||||
Object style = map.get("api_style");
|
||||
vo.setApiStyle(style == null ? "auto" : normalizeApiStyle(String.valueOf(style)));
|
||||
Object headers = map.get("extra_headers");
|
||||
if (headers instanceof Map<?, ?> m) {
|
||||
Map<String, String> h = new HashMap<>();
|
||||
|
||||
@@ -53,6 +53,8 @@ export namespace AgentVO {
|
||||
configured: boolean;
|
||||
baseUrl?: string | null;
|
||||
displayName?: string | null;
|
||||
/** auto | completions | responses */
|
||||
apiStyle?: string | null;
|
||||
apiKeyMasked?: string | null;
|
||||
models?: LlmModelItem[];
|
||||
updateTime?: string;
|
||||
@@ -140,6 +142,7 @@ export async function createAgentLlmProviderApi(body: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
displayName?: string;
|
||||
apiStyle?: string;
|
||||
}) {
|
||||
return requestClient.post<AgentVO.LlmProvider>(
|
||||
'/company/agent-llm-providers',
|
||||
@@ -149,7 +152,12 @@ export async function createAgentLlmProviderApi(body: {
|
||||
|
||||
export async function updateAgentLlmProviderApi(
|
||||
providerId: number,
|
||||
body: { baseUrl?: string; apiKey?: string; displayName?: string },
|
||||
body: {
|
||||
baseUrl?: string;
|
||||
apiKey?: string;
|
||||
displayName?: string;
|
||||
apiStyle?: string;
|
||||
},
|
||||
) {
|
||||
return requestClient.put<AgentVO.LlmProvider>(
|
||||
`/company/agent-llm-providers/${providerId}`,
|
||||
|
||||
@@ -113,10 +113,8 @@ const UserIcon = createIconifyIcon('lucide:user');
|
||||
const MemoryIcon = createIconifyIcon('lucide:brain');
|
||||
// 意见反馈图标
|
||||
const FeedbackIcon = createIconifyIcon('lucide:message-square-plus');
|
||||
// 锁图标
|
||||
const LockIcon = createIconifyIcon('lucide:lock');
|
||||
|
||||
/** 是否具备智能助手聊天权限(用于「我的记忆」入口;含超管) */
|
||||
/** 是否具备智能助手聊天权限(用于「助手记忆」入口;含超管) */
|
||||
const canUseAgentChat = computed(() => hasPermission('agent:chat'));
|
||||
|
||||
/** 当前用户可切换的可用公司数 */
|
||||
@@ -128,22 +126,22 @@ const companyCount = computed(() => {
|
||||
const menus = computed(() => {
|
||||
const menuItems = [];
|
||||
|
||||
// 个人信息
|
||||
// 个人中心
|
||||
menuItems.push({
|
||||
handler: () => {
|
||||
router.push('/system/profile');
|
||||
},
|
||||
icon: UserIcon,
|
||||
text: '个人信息',
|
||||
text: '个人中心',
|
||||
});
|
||||
// 我的记忆(有助手聊天权才显示)
|
||||
// 助手记忆(有助手聊天权才显示)
|
||||
if (canUseAgentChat.value) {
|
||||
menuItems.push({
|
||||
handler: () => {
|
||||
router.push('/agent/memories');
|
||||
},
|
||||
icon: MemoryIcon,
|
||||
text: '我的记忆',
|
||||
text: '助手记忆',
|
||||
});
|
||||
}
|
||||
// 意见反馈
|
||||
@@ -154,14 +152,6 @@ const menus = computed(() => {
|
||||
icon: FeedbackIcon,
|
||||
text: '意见反馈',
|
||||
});
|
||||
// 修改密码
|
||||
menuItems.push({
|
||||
handler: () => {
|
||||
router.push('/system/change-password');
|
||||
},
|
||||
icon: LockIcon,
|
||||
text: '修改密码',
|
||||
});
|
||||
|
||||
// 可切换公司数大于 1 时显示切换公司
|
||||
if (companyCount.value > 1) {
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
/**
|
||||
* 修改密码静态路由
|
||||
* 修改密码:并入个人中心,保留旧路径兼容跳转
|
||||
*/
|
||||
const staticRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
name: 'ChangePassword',
|
||||
path: '/system/change-password',
|
||||
component: () =>
|
||||
import(
|
||||
'#/views/sys/profile/modules/ChangePasswordModal.vue'
|
||||
),
|
||||
redirect: '/system/profile?tab=password',
|
||||
meta: {
|
||||
title: '修改密码',
|
||||
hideInMenu: true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
/**
|
||||
* 用户记忆管理(头像下拉入口;不进侧栏菜单)
|
||||
* 助手长期记忆管理(头像下拉「助手记忆」入口;不进侧栏菜单)
|
||||
*/
|
||||
const staticRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
@@ -10,7 +10,7 @@ const staticRoutes: RouteRecordRaw[] = [
|
||||
component: () => import('#/views/agent/memories/index.vue'),
|
||||
meta: {
|
||||
icon: 'lucide:brain',
|
||||
title: '我的记忆',
|
||||
title: '助手记忆',
|
||||
hideInMenu: true,
|
||||
ignoreAccess: true,
|
||||
},
|
||||
|
||||
@@ -5,14 +5,16 @@ import type { RouteRecordRaw } from 'vue-router';
|
||||
*/
|
||||
const staticRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
name: 'PersonalProfile',
|
||||
name: 'PersonalCenter',
|
||||
path: '/system/profile',
|
||||
component: () => import('#/views/sys/profile/index.vue'),
|
||||
meta: {
|
||||
icon: 'lucide:user',
|
||||
title: '个人信息',
|
||||
title: '个人中心',
|
||||
hideInMenu: true,
|
||||
ignoreAccess: true,
|
||||
// 页内 ?tab= 不另开系统标签
|
||||
fullPathKey: false,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
+22
-1
@@ -10,6 +10,7 @@ import {
|
||||
FormItem,
|
||||
Input,
|
||||
InputPassword,
|
||||
Select,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
@@ -28,8 +29,18 @@ const form = ref({
|
||||
baseUrl: '',
|
||||
apiKey: '',
|
||||
displayName: '',
|
||||
apiStyle: 'auto',
|
||||
});
|
||||
|
||||
const apiStyleOptions = [
|
||||
{
|
||||
value: 'auto',
|
||||
label: '自动(优先 Responses+store,失败再降级)',
|
||||
},
|
||||
{ value: 'completions', label: 'Chat Completions' },
|
||||
{ value: 'responses', label: 'Responses API' },
|
||||
];
|
||||
|
||||
const isEdit = computed(() => !!editing.value);
|
||||
const modalTitle = computed(() =>
|
||||
isEdit.value ? '编辑提供商' : '添加提供商',
|
||||
@@ -52,7 +63,8 @@ function open(row?: AgentVO.LlmProvider) {
|
||||
baseUrl: row?.baseUrl || '',
|
||||
apiKey: '',
|
||||
displayName: row?.displayName || '',
|
||||
};
|
||||
apiStyle: row?.apiStyle || 'auto',
|
||||
};
|
||||
modalApi.setState({ title: modalTitle.value });
|
||||
modalApi.open();
|
||||
}
|
||||
@@ -74,6 +86,7 @@ async function handleSubmit() {
|
||||
baseUrl: form.value.baseUrl.trim(),
|
||||
apiKey: form.value.apiKey.trim() || undefined,
|
||||
displayName: form.value.displayName.trim(),
|
||||
apiStyle: form.value.apiStyle,
|
||||
});
|
||||
message.success('已保存');
|
||||
} else {
|
||||
@@ -81,6 +94,7 @@ async function handleSubmit() {
|
||||
baseUrl: form.value.baseUrl.trim(),
|
||||
apiKey: form.value.apiKey.trim(),
|
||||
displayName: form.value.displayName.trim() || undefined,
|
||||
apiStyle: form.value.apiStyle,
|
||||
});
|
||||
message.success('已创建');
|
||||
}
|
||||
@@ -116,6 +130,13 @@ defineExpose({ open });
|
||||
>
|
||||
<InputPassword v-model:value="form.apiKey" placeholder="sk-..." />
|
||||
</FormItem>
|
||||
<FormItem label="API 协议">
|
||||
<Select
|
||||
v-model:value="form.apiStyle"
|
||||
:options="apiStyleOptions"
|
||||
class="w-full"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem label="备注(可选)">
|
||||
<Input v-model:value="form.displayName" placeholder="如 DeepSeek" />
|
||||
</FormItem>
|
||||
|
||||
@@ -65,6 +65,19 @@ const baseColumns: VxeGridProps<ProviderRow>['columns'] = [
|
||||
minWidth: 220,
|
||||
showOverflow: 'tooltip',
|
||||
},
|
||||
{
|
||||
field: 'apiStyle',
|
||||
title: 'API 协议',
|
||||
minWidth: 120,
|
||||
formatter: ({ row }) => {
|
||||
const m: Record<string, string> = {
|
||||
auto: '自动',
|
||||
completions: 'Completions',
|
||||
responses: 'Responses',
|
||||
};
|
||||
return m[row.apiStyle || 'auto'] || row.apiStyle || '自动';
|
||||
},
|
||||
},
|
||||
{
|
||||
field: 'apiKeyMasked',
|
||||
title: 'API Key',
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
<script lang="ts" setup>
|
||||
import { onMounted, ref } from 'vue';
|
||||
/**
|
||||
* 助手长期记忆:Page + VXE 表格(与反馈/API Key 等列表页一致)。
|
||||
*/
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { Button, Card, Empty, Spin, message } from 'ant-design-vue';
|
||||
import { EllipsisText, Page } from '@vben/common-ui';
|
||||
|
||||
import { Alert, Button, Modal, Popconfirm, Space, Tag, message } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
deleteAgentMemoryApi,
|
||||
listAgentMemoriesApi,
|
||||
@@ -13,79 +19,193 @@ import {
|
||||
|
||||
defineOptions({ name: 'AgentMemories' });
|
||||
|
||||
const loading = ref(true);
|
||||
const memories = ref<AgentVO.Memory[]>([]);
|
||||
const loading = ref(false);
|
||||
|
||||
async function loadMemories() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await listAgentMemoriesApi();
|
||||
memories.value = res.items || [];
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载记忆失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
const KIND_META: Record<string, { color: string; label: string }> = {
|
||||
note: { color: 'blue', label: '笔记' },
|
||||
preference: { color: 'purple', label: '偏好' },
|
||||
fact: { color: 'green', label: '事实' },
|
||||
};
|
||||
|
||||
function kindMeta(kind?: string) {
|
||||
const k = (kind || 'note').trim() || 'note';
|
||||
return KIND_META[k] || { color: 'default', label: k };
|
||||
}
|
||||
|
||||
async function removeMemory(id: string) {
|
||||
function formatTime(raw?: string) {
|
||||
if (!raw) return '—';
|
||||
// 后端多为 ISO;展示时去掉过长毫秒/Z
|
||||
return raw.replace('T', ' ').replace(/\.\d+Z?$/, '').replace(/Z$/, '');
|
||||
}
|
||||
|
||||
const gridOptions: VxeGridProps<AgentVO.Memory> = {
|
||||
columns: [
|
||||
{ type: 'seq', width: 56, title: '序号' },
|
||||
{
|
||||
field: 'kind',
|
||||
title: '类型',
|
||||
width: 96,
|
||||
slots: { default: 'kind' },
|
||||
},
|
||||
{
|
||||
field: 'summary',
|
||||
title: '摘要',
|
||||
minWidth: 200,
|
||||
slots: { default: 'summary' },
|
||||
},
|
||||
{
|
||||
field: 'text',
|
||||
title: '原文',
|
||||
minWidth: 240,
|
||||
slots: { default: 'text' },
|
||||
},
|
||||
{
|
||||
field: 'key',
|
||||
title: '键',
|
||||
width: 120,
|
||||
showOverflow: 'tooltip',
|
||||
formatter: ({ cellValue }) => cellValue || '—',
|
||||
},
|
||||
{
|
||||
field: 'updatedAt',
|
||||
title: '更新时间',
|
||||
width: 176,
|
||||
formatter: ({ cellValue }) => formatTime(cellValue),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 96,
|
||||
fixed: 'right',
|
||||
slots: { default: 'action' },
|
||||
},
|
||||
],
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true },
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
},
|
||||
pagerConfig: {
|
||||
enabled: true,
|
||||
pageSizes: [10, 20, 50],
|
||||
layouts: ['Total', 'Sizes', 'PrevPage', 'Number', 'NextPage'],
|
||||
},
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async ({ page }) => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await listAgentMemoriesApi();
|
||||
const all = res.items || [];
|
||||
const pageSize = page.pageSize || 20;
|
||||
const current = page.currentPage || 1;
|
||||
const start = (current - 1) * pageSize;
|
||||
return {
|
||||
items: all.slice(start, start + pageSize),
|
||||
total: all.length,
|
||||
};
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载记忆失败');
|
||||
return { items: [], total: 0 };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
|
||||
|
||||
async function removeMemory(row: AgentVO.Memory) {
|
||||
try {
|
||||
await deleteAgentMemoryApi(id);
|
||||
memories.value = memories.value.filter((m) => m.id !== id);
|
||||
message.success('已删除记忆');
|
||||
await deleteAgentMemoryApi(row.id);
|
||||
message.success('已删除');
|
||||
await gridApi.reload();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadMemories();
|
||||
});
|
||||
function clearAll() {
|
||||
Modal.confirm({
|
||||
title: '清空全部助手记忆?',
|
||||
content: '将逐条删除当前列表中的记忆,且不可恢复。',
|
||||
okText: '清空',
|
||||
okType: 'danger',
|
||||
cancelText: '取消',
|
||||
async onOk() {
|
||||
const res = await listAgentMemoriesApi();
|
||||
const items = res.items || [];
|
||||
for (const m of items) {
|
||||
await deleteAgentMemoryApi(m.id);
|
||||
}
|
||||
message.success(items.length ? `已清空 ${items.length} 条` : '暂无记忆');
|
||||
await gridApi.reload();
|
||||
},
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page auto-content-height>
|
||||
<div class="relative mx-auto max-w-3xl pb-8">
|
||||
<div
|
||||
v-if="loading"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
||||
>
|
||||
<Spin />
|
||||
</div>
|
||||
<Page
|
||||
auto-content-height
|
||||
title="助手记忆"
|
||||
description="智能助手跨会话保存的称呼、偏好与事实,按需检索,不会默认整包注入对话。"
|
||||
>
|
||||
<Alert
|
||||
type="info"
|
||||
show-icon
|
||||
class="mb-4"
|
||||
message="在智能助手里发送「记住:……」即可写入;不需要的条目可随时删除。"
|
||||
/>
|
||||
|
||||
<Card title="我的记忆" :bordered="false">
|
||||
<p class="text-muted-foreground mb-4 text-sm">
|
||||
在智能助手对话中发送「记住:…」可写入;助手按需检索,不会默认注入全部记忆。
|
||||
</p>
|
||||
<Empty
|
||||
v-if="!loading && memories.length === 0"
|
||||
description="暂无记忆"
|
||||
/>
|
||||
<div
|
||||
v-for="m in memories"
|
||||
:key="m.id"
|
||||
class="mb-2 flex items-start gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm"
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<Space>
|
||||
<Button danger @click="clearAll">清空全部</Button>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
<template #kind="{ row }">
|
||||
<Tag :color="kindMeta(row.kind).color">
|
||||
{{ kindMeta(row.kind).label }}
|
||||
</Tag>
|
||||
</template>
|
||||
|
||||
<template #summary="{ row }">
|
||||
<EllipsisText :max-width="360" tooltip-when-ellipsis>
|
||||
{{ row.summary || row.text || '—' }}
|
||||
</EllipsisText>
|
||||
</template>
|
||||
|
||||
<template #text="{ row }">
|
||||
<EllipsisText
|
||||
v-if="row.summary && row.text && row.summary !== row.text"
|
||||
:max-width="420"
|
||||
tooltip-when-ellipsis
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="break-words">{{ m.summary || m.text }}</div>
|
||||
<div
|
||||
v-if="m.summary && m.text && m.summary !== m.text"
|
||||
class="text-muted-foreground mt-1 break-words text-xs"
|
||||
>
|
||||
{{ m.text }}
|
||||
</div>
|
||||
<div
|
||||
v-if="m.updatedAt"
|
||||
class="text-muted-foreground mt-1 text-xs"
|
||||
>
|
||||
{{ m.updatedAt }}
|
||||
</div>
|
||||
</div>
|
||||
<Button type="link" size="small" danger @click="removeMemory(m.id)">
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
{{ row.text }}
|
||||
</EllipsisText>
|
||||
<span v-else class="text-muted-foreground">—</span>
|
||||
</template>
|
||||
|
||||
<template #action="{ row }">
|
||||
<Popconfirm
|
||||
title="确定删除这条记忆?"
|
||||
ok-text="删除"
|
||||
cancel-text="取消"
|
||||
ok-type="danger"
|
||||
@confirm="removeMemory(row)"
|
||||
>
|
||||
<Button type="link" size="small" danger>删除</Button>
|
||||
</Popconfirm>
|
||||
</template>
|
||||
</Grid>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
@@ -1,279 +1,87 @@
|
||||
<script lang="ts" setup>
|
||||
import type { UserDTO, UserVO } from '#/api/sys/user/types';
|
||||
import type { MenuProps } from 'ant-design-vue';
|
||||
|
||||
import { computed, reactive, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
||||
import { Menu } from 'ant-design-vue';
|
||||
|
||||
import { getUserInfoApi, updateUserInfoApi } from '#/api/sys/user';
|
||||
import { FileCategory } from '#/constants/file-category';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import ChangePasswordCard from './modules/ChangePasswordCard.vue';
|
||||
import ProfileInfoCard from './modules/ProfileInfoCard.vue';
|
||||
|
||||
defineOptions({ name: 'PersonalProfile' });
|
||||
defineOptions({ name: 'PersonalCenter' });
|
||||
|
||||
type TabKey = 'password' | 'profile';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const loading = ref(false);
|
||||
const submitting = ref(false);
|
||||
const userInfo = ref<UserVO.UserInfoVO | null>(null);
|
||||
const avatarLoading = ref(false);
|
||||
const ProfileIcon = createIconifyIcon('lucide:user');
|
||||
const LockIcon = createIconifyIcon('lucide:lock');
|
||||
|
||||
// 待上传的头像文件(用户选择后先缓存,保存时再上传)
|
||||
const pendingAvatarFile = ref<File | null>(null);
|
||||
const activeTab = ref<TabKey>('profile');
|
||||
const selectedKeys = computed(() => [activeTab.value]);
|
||||
|
||||
// 计算属性:头像显示优先级:本地预览 > 已保存的头像 > 初始头像
|
||||
const avatarSrc = computed(() => {
|
||||
if (pendingAvatarFile.value) {
|
||||
return URL.createObjectURL(pendingAvatarFile.value);
|
||||
/**
|
||||
* 页内切换只改本地状态,不要改 query。
|
||||
* tabbar 用 fullPath 做标签 key,带 ?tab= 会开出两个系统标签。
|
||||
*/
|
||||
const onMenuClick: MenuProps['onClick'] = ({ key }) => {
|
||||
activeTab.value = key === 'password' ? 'password' : 'profile';
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
// 兼容 /system/change-password → ?tab=password:读一次后清掉 query
|
||||
if (route.query.tab === 'password') {
|
||||
activeTab.value = 'password';
|
||||
void router.replace({ path: route.path, query: {} });
|
||||
}
|
||||
if (userInfo.value?.avatar) {
|
||||
return userInfo.value.avatar;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
// 表单数据(与更新接口 DTO 一致,头像 ID 用 undefined 表示未变更/未上传)
|
||||
const formData = reactive<UserDTO.UpdateUserInfoDTO>({
|
||||
username: '',
|
||||
realName: '',
|
||||
phone: '',
|
||||
remark: '',
|
||||
});
|
||||
|
||||
const formRef = ref<any>(null);
|
||||
|
||||
async function fetchUserInfo() {
|
||||
try {
|
||||
loading.value = true;
|
||||
const data = await getUserInfoApi();
|
||||
userInfo.value = data;
|
||||
formData.username = data.username || '';
|
||||
formData.realName = data.realName || '';
|
||||
formData.phone = data.phone || '';
|
||||
formData.remark = data.remark || '';
|
||||
// 重置待上传的头像
|
||||
pendingAvatarFile.value = null;
|
||||
} catch (error) {
|
||||
console.error('获取用户信息失败:', error);
|
||||
message.error('获取用户信息失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleAvatarChange({ file }: { file: any }) {
|
||||
// 获取实际文件对象
|
||||
const actualFile = file.originFileObj || file;
|
||||
if (!actualFile) return;
|
||||
|
||||
if (!actualFile.type.startsWith('image/')) {
|
||||
message.error('只能上传图片文件');
|
||||
return;
|
||||
}
|
||||
if (actualFile.size > 2 * 1024 * 1024) {
|
||||
message.error('图片大小不能超过 2MB');
|
||||
return;
|
||||
}
|
||||
|
||||
// 缓存头像文件,预览由 computed avatarSrc 自动处理
|
||||
pendingAvatarFile.value = actualFile;
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
submitting.value = true;
|
||||
|
||||
// 如果有待上传的头像,先上传
|
||||
if (pendingAvatarFile.value) {
|
||||
avatarLoading.value = true;
|
||||
try {
|
||||
const fileInfo = await uploadFile(pendingAvatarFile.value, {
|
||||
category: FileCategory.AVATAR,
|
||||
errorMessage: '头像上传失败',
|
||||
});
|
||||
formData.avatarImageId = fileInfo.id;
|
||||
} finally {
|
||||
avatarLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
await updateUserInfoApi(formData);
|
||||
message.success('保存成功');
|
||||
formData.avatarImageId = undefined;
|
||||
await fetchUserInfo();
|
||||
} catch (error: any) {
|
||||
if (error?.errorFields) {
|
||||
return;
|
||||
}
|
||||
console.error('保存失败:', error);
|
||||
message.error('保存失败');
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
if (userInfo.value) {
|
||||
formData.username = userInfo.value.username || '';
|
||||
formData.realName = userInfo.value.realName || '';
|
||||
formData.phone = userInfo.value.phone || '';
|
||||
formData.remark = userInfo.value.remark || '';
|
||||
}
|
||||
formData.avatarImageId = undefined;
|
||||
formRef.value?.resetFields();
|
||||
pendingAvatarFile.value = null;
|
||||
}
|
||||
|
||||
fetchUserInfo();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page
|
||||
title="个人信息"
|
||||
auto-content-height
|
||||
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<div class="mx-auto max-w-2xl">
|
||||
<Spin :spinning="loading">
|
||||
<Page auto-content-height content-class="flex min-h-0 flex-col">
|
||||
<div
|
||||
class="flex min-h-0 flex-1 overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<aside
|
||||
class="flex w-52 shrink-0 flex-col border-r border-slate-100 bg-slate-50/60 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]"
|
||||
>
|
||||
<div
|
||||
class="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
class="border-b border-slate-100 px-4 py-4 text-sm font-medium text-slate-600 dark:border-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
<!-- 头部 -->
|
||||
<div class="border-b border-slate-100 bg-slate-50/50 px-8 py-6 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 class="text-xl font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
个人信息
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
编辑您的个人信息和头像
|
||||
</p>
|
||||
</div>
|
||||
<Button type="link" class="!px-0" @click="router.push('/feedback')">
|
||||
意见反馈
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 表单 -->
|
||||
<div class="px-8 py-6">
|
||||
<Form
|
||||
ref="formRef"
|
||||
:model="formData"
|
||||
layout="vertical"
|
||||
class="space-y-6"
|
||||
>
|
||||
<!-- 头像 -->
|
||||
<div class="flex items-center">
|
||||
<div class="mr-6">
|
||||
<Upload
|
||||
@change="handleAvatarChange"
|
||||
:show-upload-list="false"
|
||||
accept="image/*"
|
||||
>
|
||||
<div class="relative cursor-pointer">
|
||||
<Spin
|
||||
v-if="avatarLoading"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-white/80"
|
||||
/>
|
||||
<img
|
||||
v-if="avatarSrc"
|
||||
:src="avatarSrc"
|
||||
alt="头像"
|
||||
class="h-24 w-24 rounded-full object-cover"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex h-24 w-24 items-center justify-center rounded-full bg-slate-200 text-2xl text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
{{ userInfo?.realName?.charAt(0) || '?' }}
|
||||
</div>
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity hover:opacity-100"
|
||||
>
|
||||
<span class="text-sm text-white">点击更换</span>
|
||||
</div>
|
||||
</div>
|
||||
</Upload>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
头像
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
点击选择新头像,保存后生效,建议大小不超过 2MB
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 登录用户名(可选,用于账号登录) -->
|
||||
<Form.Item
|
||||
label="登录用户名"
|
||||
name="username"
|
||||
:rules="[
|
||||
{ min: 3, max: 20, message: '登录用户名长度为3-20个字符' },
|
||||
{
|
||||
pattern: /^$|^[a-zA-Z0-9_]+$/,
|
||||
message: '登录用户名只能包含字母、数字和下划线',
|
||||
},
|
||||
]"
|
||||
>
|
||||
<Input
|
||||
v-model:value="formData.username"
|
||||
placeholder="可选,设置后可用账号登录"
|
||||
allow-clear
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 真实姓名 -->
|
||||
<Form.Item
|
||||
label="真实姓名"
|
||||
name="realName"
|
||||
:rules="[{ required: true, message: '请输入真实姓名' }]"
|
||||
>
|
||||
<Input v-model:value="formData.realName" placeholder="请输入真实姓名" />
|
||||
</Form.Item>
|
||||
|
||||
<!-- 手机号 -->
|
||||
<Form.Item
|
||||
label="手机号"
|
||||
name="phone"
|
||||
:rules="[
|
||||
{ required: true, message: '请输入手机号' },
|
||||
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
|
||||
]"
|
||||
>
|
||||
<Input
|
||||
v-model:value="formData.phone"
|
||||
placeholder="请输入手机号"
|
||||
:maxlength="11"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 备注 -->
|
||||
<Form.Item label="备注" name="remark">
|
||||
<Input.TextArea
|
||||
v-model:value="formData.remark"
|
||||
placeholder="请输入备注"
|
||||
:rows="3"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</div>
|
||||
|
||||
<!-- 底部按钮 -->
|
||||
<div class="flex justify-end gap-3 border-t border-slate-100 bg-slate-50/50 px-8 py-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
||||
<Button @click="handleReset">重置</Button>
|
||||
<Button type="primary" :loading="submitting" @click="handleSubmit">
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
设置
|
||||
</div>
|
||||
</Spin>
|
||||
<Menu
|
||||
:selected-keys="selectedKeys"
|
||||
mode="inline"
|
||||
class="!border-none !bg-transparent"
|
||||
@click="onMenuClick"
|
||||
>
|
||||
<Menu.Item key="profile">
|
||||
<template #icon>
|
||||
<ProfileIcon class="size-4" />
|
||||
</template>
|
||||
个人信息
|
||||
</Menu.Item>
|
||||
<Menu.Item key="password">
|
||||
<template #icon>
|
||||
<LockIcon class="size-4" />
|
||||
</template>
|
||||
修改密码
|
||||
</Menu.Item>
|
||||
</Menu>
|
||||
</aside>
|
||||
|
||||
<div class="min-h-0 min-w-0 flex-1 overflow-y-auto p-6">
|
||||
<div class="mx-auto max-w-2xl">
|
||||
<ProfileInfoCard v-if="activeTab === 'profile'" />
|
||||
<ChangePasswordCard v-else />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
<script lang="ts" setup>
|
||||
import type { FormItemProps } from 'ant-design-vue';
|
||||
|
||||
import { reactive, ref } from 'vue';
|
||||
|
||||
import { Button, Form, Input, message } from 'ant-design-vue';
|
||||
|
||||
import { changePasswordApi } from '#/api/core/auth';
|
||||
|
||||
defineOptions({ name: 'ChangePasswordCard' });
|
||||
|
||||
const loading = ref(false);
|
||||
const formRef = ref<any>(null);
|
||||
const formData = reactive({
|
||||
oldPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
|
||||
/** 确认密码校验放在 script,避免模板内 Promise 被误解析 */
|
||||
const confirmPasswordRules: NonNullable<FormItemProps['rules']> = [
|
||||
{
|
||||
required: true,
|
||||
async validator(_rule: unknown, value: string) {
|
||||
if (!value?.trim()) {
|
||||
throw new Error('请确认密码');
|
||||
}
|
||||
if (value !== formData.newPassword) {
|
||||
throw new Error('两次输入的密码不一致');
|
||||
}
|
||||
},
|
||||
trigger: 'change',
|
||||
},
|
||||
];
|
||||
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
await changePasswordApi({
|
||||
oldPassword: formData.oldPassword,
|
||||
newPassword: formData.newPassword,
|
||||
});
|
||||
message.success('密码修改成功');
|
||||
handleReset();
|
||||
} catch (err: any) {
|
||||
message.error(err?.message || '密码修改失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
formRef.value?.resetFields();
|
||||
formData.oldPassword = '';
|
||||
formData.newPassword = '';
|
||||
formData.confirmPassword = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="mb-6">
|
||||
<h2 class="text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
修改密码
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
请妥善保管您的新密码
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Form ref="formRef" :model="formData" layout="vertical">
|
||||
<Form.Item
|
||||
label="旧密码"
|
||||
name="oldPassword"
|
||||
:rules="[{ required: true, message: '请输入旧密码' }]"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.oldPassword"
|
||||
placeholder="请输入旧密码"
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="新密码"
|
||||
name="newPassword"
|
||||
:rules="[
|
||||
{ required: true, message: '请输入新密码' },
|
||||
{ min: 6, max: 20, message: '密码长度为6-20个字符' },
|
||||
]"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.newPassword"
|
||||
placeholder="请输入新密码"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="确认密码"
|
||||
name="confirmPassword"
|
||||
:rules="confirmPasswordRules"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.confirmPassword"
|
||||
placeholder="请再次输入新密码"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<div class="mt-2 flex justify-end gap-3">
|
||||
<Button @click="handleReset">重置</Button>
|
||||
<Button type="primary" :loading="loading" @click="handleSubmit">
|
||||
确定
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,147 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import { reactive, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import type { FormItemProps } from 'ant-design-vue';
|
||||
|
||||
import { Button, Form, Input, message, Spin } from 'ant-design-vue';
|
||||
|
||||
import { changePasswordApi } from '#/api/core/auth';
|
||||
|
||||
defineOptions({ name: 'ChangePassword' });
|
||||
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
|
||||
const formRef = ref<any>(null);
|
||||
const formData = reactive({
|
||||
oldPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
|
||||
/** 放在 script 中,避免模板内联 validator 里 Promise 被误解析为组件属性 */
|
||||
const confirmPasswordRules: NonNullable<FormItemProps['rules']> = [
|
||||
{
|
||||
required: true,
|
||||
async validator(_rule: unknown, value: string) {
|
||||
if (!value?.trim()) {
|
||||
throw new Error('请确认密码');
|
||||
}
|
||||
if (value !== formData.newPassword) {
|
||||
throw new Error('两次输入的密码不一致');
|
||||
}
|
||||
},
|
||||
trigger: 'change',
|
||||
},
|
||||
];
|
||||
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
await changePasswordApi({
|
||||
oldPassword: formData.oldPassword,
|
||||
newPassword: formData.newPassword,
|
||||
});
|
||||
message.success('密码修改成功');
|
||||
formRef.value?.resetFields();
|
||||
router.push('/system/profile');
|
||||
} catch (err: any) {
|
||||
message.error(err?.message || '密码修改失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
formRef.value?.resetFields();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page
|
||||
title="修改密码"
|
||||
auto-content-height
|
||||
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<div class="mx-auto max-w-2xl">
|
||||
<div
|
||||
class="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<!-- 头部 -->
|
||||
<div class="border-b border-slate-100 bg-slate-50/50 px-8 py-6 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
||||
<h2 class="text-xl font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
修改密码
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
请妥善保管您的新密码
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 表单 -->
|
||||
<div class="px-8 py-6">
|
||||
<Spin :spinning="loading">
|
||||
<Form
|
||||
ref="formRef"
|
||||
:model="formData"
|
||||
layout="vertical"
|
||||
class="space-y-6"
|
||||
>
|
||||
<!-- 旧密码 -->
|
||||
<Form.Item
|
||||
label="旧密码"
|
||||
name="oldPassword"
|
||||
:rules="[{ required: true, message: '请输入旧密码' }]"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.oldPassword"
|
||||
placeholder="请输入旧密码"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 新密码 -->
|
||||
<Form.Item
|
||||
label="新密码"
|
||||
name="newPassword"
|
||||
:rules="[{ required: true, message: '请输入新密码' }]"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.newPassword"
|
||||
placeholder="请输入新密码"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 确认密码 -->
|
||||
<Form.Item
|
||||
label="确认密码"
|
||||
name="confirmPassword"
|
||||
:rules="confirmPasswordRules"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.confirmPassword"
|
||||
placeholder="请再次输入新密码"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Spin>
|
||||
</div>
|
||||
|
||||
<!-- 底部按钮 -->
|
||||
<div class="flex justify-end gap-3 border-t border-slate-100 bg-slate-50/50 px-8 py-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
||||
<Button @click="handleReset">重置</Button>
|
||||
<Button type="primary" :loading="loading" @click="handleSubmit">
|
||||
确定
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
@@ -0,0 +1,242 @@
|
||||
<script lang="ts" setup>
|
||||
import type { UserDTO, UserVO } from '#/api/sys/user/types';
|
||||
|
||||
import { computed, reactive, ref } from 'vue';
|
||||
|
||||
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
||||
|
||||
import { getUserInfoApi, updateUserInfoApi } from '#/api/sys/user';
|
||||
import { FileCategory } from '#/constants/file-category';
|
||||
import { useAuthStore } from '#/store';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
|
||||
defineOptions({ name: 'ProfileInfoCard' });
|
||||
|
||||
const authStore = useAuthStore();
|
||||
|
||||
const loading = ref(false);
|
||||
const submitting = ref(false);
|
||||
const userInfo = ref<UserVO.UserInfoVO | null>(null);
|
||||
const avatarLoading = ref(false);
|
||||
const pendingAvatarFile = ref<File | null>(null);
|
||||
|
||||
const avatarSrc = computed(() => {
|
||||
if (pendingAvatarFile.value) {
|
||||
return URL.createObjectURL(pendingAvatarFile.value);
|
||||
}
|
||||
if (userInfo.value?.avatar) {
|
||||
return userInfo.value.avatar;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const formData = reactive<UserDTO.UpdateUserInfoDTO>({
|
||||
username: '',
|
||||
realName: '',
|
||||
phone: '',
|
||||
remark: '',
|
||||
});
|
||||
|
||||
const formRef = ref<any>(null);
|
||||
|
||||
async function fetchUserInfo() {
|
||||
try {
|
||||
loading.value = true;
|
||||
const data = await getUserInfoApi();
|
||||
userInfo.value = data;
|
||||
formData.username = data.username || '';
|
||||
formData.realName = data.realName || '';
|
||||
formData.phone = data.phone || '';
|
||||
formData.remark = data.remark || '';
|
||||
pendingAvatarFile.value = null;
|
||||
} catch (error) {
|
||||
console.error('获取用户信息失败:', error);
|
||||
message.error('获取用户信息失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleAvatarChange({ file }: { file: any }) {
|
||||
const actualFile = file.originFileObj || file;
|
||||
if (!actualFile) return;
|
||||
|
||||
if (!actualFile.type.startsWith('image/')) {
|
||||
message.error('只能上传图片文件');
|
||||
return;
|
||||
}
|
||||
if (actualFile.size > 2 * 1024 * 1024) {
|
||||
message.error('图片大小不能超过 2MB');
|
||||
return;
|
||||
}
|
||||
pendingAvatarFile.value = actualFile;
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
submitting.value = true;
|
||||
|
||||
if (pendingAvatarFile.value) {
|
||||
avatarLoading.value = true;
|
||||
try {
|
||||
const fileInfo = await uploadFile(pendingAvatarFile.value, {
|
||||
category: FileCategory.AVATAR,
|
||||
errorMessage: '头像上传失败',
|
||||
});
|
||||
formData.avatarImageId = fileInfo.id;
|
||||
} finally {
|
||||
avatarLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
await updateUserInfoApi(formData);
|
||||
message.success('保存成功');
|
||||
formData.avatarImageId = undefined;
|
||||
await fetchUserInfo();
|
||||
await authStore.fetchUserInfo();
|
||||
} catch (error: any) {
|
||||
if (error?.errorFields) {
|
||||
return;
|
||||
}
|
||||
console.error('保存失败:', error);
|
||||
message.error('保存失败');
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
if (userInfo.value) {
|
||||
formData.username = userInfo.value.username || '';
|
||||
formData.realName = userInfo.value.realName || '';
|
||||
formData.phone = userInfo.value.phone || '';
|
||||
formData.remark = userInfo.value.remark || '';
|
||||
}
|
||||
formData.avatarImageId = undefined;
|
||||
formRef.value?.resetFields();
|
||||
pendingAvatarFile.value = null;
|
||||
}
|
||||
|
||||
fetchUserInfo();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="mb-6">
|
||||
<h2 class="text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
个人信息
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
编辑头像、登录用户名与联系方式
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Spin :spinning="loading">
|
||||
<Form ref="formRef" :model="formData" layout="vertical">
|
||||
<div class="mb-6 flex items-center">
|
||||
<div class="mr-5">
|
||||
<Upload
|
||||
accept="image/*"
|
||||
:show-upload-list="false"
|
||||
@change="handleAvatarChange"
|
||||
>
|
||||
<div class="relative cursor-pointer">
|
||||
<Spin
|
||||
v-if="avatarLoading"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-white/80"
|
||||
/>
|
||||
<img
|
||||
v-if="avatarSrc"
|
||||
:src="avatarSrc"
|
||||
alt="头像"
|
||||
class="h-20 w-20 rounded-full object-cover"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex h-20 w-20 items-center justify-center rounded-full bg-slate-200 text-xl text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
{{ userInfo?.realName?.charAt(0) || '?' }}
|
||||
</div>
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity hover:opacity-100"
|
||||
>
|
||||
<span class="text-xs text-white">更换</span>
|
||||
</div>
|
||||
</div>
|
||||
</Upload>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
头像
|
||||
</p>
|
||||
<p
|
||||
class="mt-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
点击更换,保存后生效,不超过 2MB
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Form.Item
|
||||
label="登录用户名"
|
||||
name="username"
|
||||
:rules="[
|
||||
{ min: 3, max: 20, message: '登录用户名长度为3-20个字符' },
|
||||
{
|
||||
pattern: /^$|^[a-zA-Z0-9_]+$/,
|
||||
message: '登录用户名只能包含字母、数字和下划线',
|
||||
},
|
||||
]"
|
||||
>
|
||||
<Input
|
||||
v-model:value="formData.username"
|
||||
allow-clear
|
||||
placeholder="可选,设置后可用账号登录"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="真实姓名"
|
||||
name="realName"
|
||||
:rules="[{ required: true, message: '请输入真实姓名' }]"
|
||||
>
|
||||
<Input
|
||||
v-model:value="formData.realName"
|
||||
placeholder="请输入真实姓名"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="手机号"
|
||||
name="phone"
|
||||
:rules="[
|
||||
{ required: true, message: '请输入手机号' },
|
||||
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
|
||||
]"
|
||||
>
|
||||
<Input
|
||||
v-model:value="formData.phone"
|
||||
:maxlength="11"
|
||||
placeholder="请输入手机号"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="备注" name="remark">
|
||||
<Input.TextArea
|
||||
v-model:value="formData.remark"
|
||||
:rows="3"
|
||||
placeholder="请输入备注"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Spin>
|
||||
|
||||
<div class="mt-2 flex justify-end gap-3">
|
||||
<Button @click="handleReset">重置</Button>
|
||||
<Button type="primary" :loading="submitting" @click="handleSubmit">
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user