59 lines
2.3 KiB
Python
59 lines
2.3 KiB
Python
from typing import Any
|
||
|
||
from sqlalchemy.orm import Session
|
||
|
||
from app.memory.service import MemoryService
|
||
|
||
MAX_FACTS_IN_CONTEXT = 25
|
||
PROFILE_KEYS = ("name", "timezone", "language", "notes")
|
||
|
||
|
||
def get_memory_snapshot(db: Session, session_id: int | None = None) -> dict[str, Any]:
|
||
return MemoryService(db).snapshot(session_id)
|
||
|
||
|
||
def format_memory_context(snapshot: dict[str, Any]) -> str:
|
||
lines = ["[Память и профиль — долгосрочный контекст]"]
|
||
|
||
profile = snapshot.get("profile") or {}
|
||
profile_lines = []
|
||
for key in PROFILE_KEYS:
|
||
value = (profile.get(key) or "").strip()
|
||
if value:
|
||
profile_lines.append(f"- {key}: {value}")
|
||
if profile_lines:
|
||
lines.append("Профиль пользователя:")
|
||
lines.extend(profile_lines)
|
||
else:
|
||
lines.append("Профиль: не заполнен (можно уточнить имя, часовой пояс).")
|
||
|
||
summary = (snapshot.get("session_summary") or "").strip()
|
||
if summary:
|
||
lines.append("")
|
||
lines.append("Сводка текущего чата (ранние сообщения):")
|
||
lines.append(summary)
|
||
|
||
facts = snapshot.get("facts") or []
|
||
if facts:
|
||
lines.append("")
|
||
lines.append(f"Запомненные факты ({snapshot.get('total_facts', len(facts))}):")
|
||
for fact in facts[:MAX_FACTS_IN_CONTEXT]:
|
||
lines.append(
|
||
f"- [{fact.get('category')}] #{fact.get('id')} {fact.get('content')}"
|
||
)
|
||
else:
|
||
lines.append("")
|
||
lines.append("Запомненные факты: пока нет.")
|
||
|
||
lines.append("")
|
||
lines.append(
|
||
"Правила памяти: "
|
||
"«запомни» → remember_fact. "
|
||
"«что ты помнишь» → recall_memories или ответ из снимка выше. "
|
||
"«забудь #N» → forget_memory. "
|
||
"Профиль (имя, timezone) → update_profile. "
|
||
"Длинный чат — update_session_summary с краткой сводкой темы. "
|
||
"Не выдумывай факты — только то, что в профиле/фактах или сказал пользователь."
|
||
)
|
||
return "\n".join(lines)
|