mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 05:09:21 +08:00
feat: 贯通 context_window 配置并按 token 预算裁剪对话历史
This commit is contained in:
@@ -12,28 +12,6 @@ from agent.tools.labels import tool_status_label
|
||||
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole, StreamEvent
|
||||
from domain.ports import ChatStreamer
|
||||
|
||||
_BASE_SYSTEM = (
|
||||
"你是电商 DMB 系统的经营助手。回答简洁、可执行、结论先行。"
|
||||
"需要经营数据时优先调用可用工具。"
|
||||
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
|
||||
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
|
||||
"你具备跨会话的用户级长期记忆,但内容不会自动注入对话。"
|
||||
"需要称呼、偏好或用户事实时:先 memory_search,必要时再 memory_load;"
|
||||
"禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
||||
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
|
||||
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
|
||||
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
|
||||
"用户要求记住:可用 memory_save,或系统提示「本轮已写入」时只简短确认内容。"
|
||||
"用户说近 N 天、昨天、本周、本月等相对日期时,先调用 get_current_time,"
|
||||
"用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查数,不要向用户索要日期范围。"
|
||||
"用户用名称或编码指代店铺、商品、SKU 时,先调用 catalog_search;"
|
||||
"恰好一条就用返回的 id 继续查数;多条只列名称和编码让用户选。"
|
||||
"用户消息含 [引用] 且带 id= 时,直接用这些 id,不必再搜索,也不要向用户复述 id。"
|
||||
"禁止向用户索要店铺 ID、商品 ID 或 SKU ID。"
|
||||
"若只给了引用、没有具体问题,按近 7 天概览回答该对象。"
|
||||
"若工具失败或无权限,请说明原因并给出可操作建议。"
|
||||
)
|
||||
|
||||
|
||||
class OpenAICompatibleStreamer(ChatStreamer):
|
||||
async def stream_reply(
|
||||
@@ -42,16 +20,10 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
llm: LlmRuntimeConfig,
|
||||
history: list[ChatMessage],
|
||||
user_text: str,
|
||||
system_prompt: str,
|
||||
tools: list[Any] | None = None,
|
||||
memory_count: int = 0,
|
||||
memory_just_saved: str | None = None,
|
||||
max_tool_result_chars: int = 8000,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
system = _BASE_SYSTEM
|
||||
if memory_count > 0:
|
||||
system += f"\n\n当前用户约有 {memory_count} 条长期记忆,需要时用 memory_search / memory_load。"
|
||||
if memory_just_saved:
|
||||
system += f"\n\n【本轮已写入长期记忆】{memory_just_saved}"
|
||||
|
||||
model = ChatOpenAI(
|
||||
api_key=llm.api_key,
|
||||
base_url=llm.base_url,
|
||||
@@ -60,7 +32,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
streaming=True,
|
||||
default_headers=llm.extra_headers or None,
|
||||
)
|
||||
messages: list[Any] = [SystemMessage(content=system)]
|
||||
messages: list[Any] = [SystemMessage(content=system_prompt)]
|
||||
for m in history:
|
||||
if m.role == MessageRole.USER:
|
||||
messages.append(HumanMessage(content=m.content))
|
||||
@@ -78,6 +50,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
# 工具轮:每轮用 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):
|
||||
gathered = None
|
||||
saw_tool = False
|
||||
@@ -99,7 +72,6 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
if not tool_calls:
|
||||
return
|
||||
|
||||
# 去重保序的工具状态(同轮多次同名只显示一次文案)
|
||||
seen: set[str] = set()
|
||||
for tc in tool_calls:
|
||||
name = tc.get("name") or ""
|
||||
@@ -129,7 +101,9 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
result = f"工具执行失败: {e}"
|
||||
messages.append(ToolMessage(content=str(result)[:8000], tool_call_id=call_id))
|
||||
messages.append(
|
||||
ToolMessage(content=str(result)[:tool_cap], tool_call_id=call_id)
|
||||
)
|
||||
|
||||
for name in seen:
|
||||
yield StreamEvent.tool(
|
||||
|
||||
@@ -43,7 +43,18 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
||||
str(k): str(v)
|
||||
for k, v in (data.get("extraHeaders") or {}).items()
|
||||
},
|
||||
context_window=_optional_positive_int(data.get("contextWindow")),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("拉取 Server LLM runtime 失败 company_id=%s", company_id)
|
||||
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
|
||||
|
||||
@@ -29,6 +29,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
api_key=data["api_key"],
|
||||
model=data["model"],
|
||||
extra_headers=data.get("extra_headers") or {},
|
||||
context_window=_optional_int(data.get("context_window")),
|
||||
)
|
||||
|
||||
async def set(self, company_id: int, config: LlmRuntimeConfig, ttl_seconds: int) -> None:
|
||||
@@ -37,6 +38,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
"api_key": config.api_key,
|
||||
"model": config.model,
|
||||
"extra_headers": config.extra_headers,
|
||||
"context_window": config.context_window,
|
||||
}
|
||||
await self._r.set(self._key(company_id), json.dumps(payload), ex=ttl_seconds)
|
||||
|
||||
@@ -47,6 +49,16 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
_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:
|
||||
|
||||
Reference in New Issue
Block a user