"""Multi-turn conversation sanitization, rolling compaction, and lightweight memory formatting.""" from __future__ import annotations import asyncio from typing import Any from app.core.logging import get_logger from app.schemas.ai import SituationalAnalysisRequest from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text from app.services.ai_client import AIProviderClient logger = get_logger(__name__, service="ai_memory") RECENT_WINDOW_TURNS = 4 COMPACT_TRIGGER_CHARS = 7500 MAX_MESSAGE_CHARS = 1800 MAX_SUMMARY_CHARS = 1600 MAX_MEMORY_NOTES = 12 MAX_PINNED_SUMMARIES = 8 def _truncate_text(text: str, limit: int) -> str: cleaned = str(text or "").strip() if len(cleaned) <= limit: return cleaned return f"{cleaned[: max(0, limit - 1)].rstrip()}…" def sanitize_history_messages(raw_messages: list[Any] | None) -> list[dict[str, str]]: """Strip inline thinking blocks, truncate extremes, and normalize alternating user/assistant turns.""" normalized: list[dict[str, str]] = [] for item in raw_messages or []: if isinstance(item, dict): role = str(item.get("role") or "").strip().lower() raw_content = item.get("content") else: role = str(getattr(item, "role", "") or "").strip().lower() raw_content = getattr(item, "content", "") if role not in {"user", "assistant"}: continue content = str(raw_content or "").strip() if not content: continue if role == "assistant": clean_content, _ = strip_thinking_text(content) content = clean_content or content content = _truncate_text(content, MAX_MESSAGE_CHARS) if not content: continue if not normalized and role == "assistant": continue if normalized and normalized[-1]["role"] == role: merged = f"{normalized[-1]['content']}\n\n{content}" normalized[-1]["content"] = _truncate_text(merged, MAX_MESSAGE_CHARS) else: normalized.append({"role": role, "content": content}) return normalized def _sanitize_short_list(items: list[Any] | None, *, max_items: int, max_chars: int = 200) -> list[str]: result: list[str] = [] seen: set[str] = set() for raw in items or []: text = _truncate_text(str(raw or "").replace("\r", " ").replace("\n", " "), max_chars) if not text or text in seen: continue seen.add(text) result.append(text) if len(result) >= max_items: break return result def sanitize_memory_notes(notes: list[Any] | None) -> list[str]: """Return deduplicated short user memory notes within configured cap.""" return _sanitize_short_list(notes, max_items=MAX_MEMORY_NOTES) def sanitize_pinned_summaries(items: list[Any] | None) -> list[str]: """Return deduplicated short pinned comparison summaries within configured cap.""" return _sanitize_short_list(items, max_items=MAX_PINNED_SUMMARIES) def build_deterministic_compaction_summary( existing_summary: str, dropped_messages: list[dict[str, str]], ) -> str: """Build a bounded structured summary when older turns overflow the active window.""" lines: list[str] = [] prior = str(existing_summary or "").strip() if prior: lines.append(prior) pair_lines: list[str] = [] idx = 0 while idx < len(dropped_messages): msg = dropped_messages[idx] if msg["role"] == "user": q = _truncate_text(msg["content"].replace("\n", " "), 120) a = "" if idx + 1 < len(dropped_messages) and dropped_messages[idx + 1]["role"] == "assistant": a = _truncate_text(dropped_messages[idx + 1]["content"].replace("\n", " "), 180) idx += 2 else: idx += 1 pair_lines.append(f"- 问:{q}" + (f" → 结:{a}" if a else "")) else: a = _truncate_text(msg["content"].replace("\n", " "), 160) pair_lines.append(f"- 历史结论:{a}") idx += 1 if pair_lines: block = "\n".join(pair_lines) if prior and not prior.startswith("### 前序对话摘要"): lines = [f"### 前序对话摘要\n{prior}", block] elif prior: lines = [prior, block] else: lines = [f"### 前序对话摘要\n{block}"] combined = "\n".join(lines).strip() if len(combined) > MAX_SUMMARY_CHARS: head = "### 前序对话摘要\n" tail_budget = MAX_SUMMARY_CHARS - len(head) - 2 combined = f"{head}…{combined[-tail_budget:].lstrip()}" return combined async def compact_conversation_history( raw_messages: list[Any] | None, existing_summary: str = "", *, ai_client: AIProviderClient | None = None, ai_ready: bool = False, recent_window_turns: int = RECENT_WINDOW_TURNS, char_budget: int = COMPACT_TRIGGER_CHARS, ) -> dict[str, Any]: """Keep recent window verbatim and compact overflow turns into a rolling summary.""" sanitized = sanitize_history_messages(raw_messages) summary = _truncate_text(existing_summary or "", MAX_SUMMARY_CHARS) keep_limit = max(2, recent_window_turns * 2) split_idx = max(0, len(sanitized) - keep_limit) if split_idx < len(sanitized) and sanitized[split_idx]["role"] == "assistant": split_idx += 1 older = sanitized[:split_idx] recent = sanitized[split_idx:] total_chars = len(summary) + sum(len(m["content"]) for m in recent) while not older and total_chars > char_budget and len(recent) > 2: move_count = 2 if (len(recent) >= 4 and recent[0]["role"] == "user" and recent[1]["role"] == "assistant") else 1 older.extend(recent[:move_count]) recent = recent[move_count:] total_chars = len(summary) + sum(len(m["content"]) for m in recent) if not older: return { "summary": summary, "recent_messages": recent, "compacted": False, "compacted_count": 0, } next_summary = "" if ai_ready and ai_client is not None: try: effective_client = ai_client if type(ai_client) is AIProviderClient and ai_client.llm_config: effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=900) transcript = "\n".join( f"{'用户' if m['role'] == 'user' else 'AI 参谋'}: {m['content']}" for m in older ) compact_req = SituationalAnalysisRequest( title="Planet 多轮对话上下文压缩摘要", objective=( "请将以下较早的多轮对话与既有摘要压缩为简明中文备忘(不超过 280 字)," "保留:1) 用户聚焦的图层/国家/新闻实体与口径边界;2) 已核验关键数据结论;" "3) 尚未完结的追问线索。严禁保留客套或编造数值。" ), system_prompt="你是精准的对话上下文压缩器,只输出精炼中文要点摘要。", context={ "existing_summary": summary or None, "archived_dialogue": transcript, }, thinking=None, ) resp = await asyncio.wait_for(effective_client.analyze(compact_req), timeout=12.0) clean_resp, _ = strip_thinking_text(str(getattr(resp, "content", "") or "")) next_summary = _truncate_text(clean_resp, MAX_SUMMARY_CHARS) except asyncio.CancelledError: raise except Exception as exc: logger.warning_event( "LLM conversation compaction fell back to deterministic summary", event="ai_memory.compaction.fallback", context={"error": str(exc), "older_count": len(older)}, ) if not next_summary: next_summary = build_deterministic_compaction_summary(summary, older) return { "summary": next_summary, "recent_messages": recent, "compacted": True, "compacted_count": len(older), }