|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from dataclasses import dataclass |
| 5 | +from typing import Optional, Sequence |
| 6 | + |
| 7 | +import asyncpg |
| 8 | + |
| 9 | +from ..config import settings |
| 10 | + |
| 11 | + |
| 12 | +def _dsn() -> str: |
| 13 | + db = settings.db |
| 14 | + return f"postgresql://{db.user}:{db.password}@{db.host}:{db.port}/{db.database}" |
| 15 | + |
| 16 | + |
| 17 | +async def _ensure_async(conn: asyncpg.Connection) -> None: |
| 18 | + await conn.execute( |
| 19 | + """ |
| 20 | + CREATE TABLE IF NOT EXISTS bot_memory ( |
| 21 | + id BIGSERIAL PRIMARY KEY, |
| 22 | + user_id BIGINT NOT NULL, |
| 23 | + guild_id BIGINT, |
| 24 | + channel_id BIGINT, |
| 25 | + role TEXT NOT NULL, -- 'user' | 'assistant' | 'system' | 'summary' |
| 26 | + kind TEXT NOT NULL DEFAULT 'message', |
| 27 | + content TEXT NOT NULL, |
| 28 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() |
| 29 | + ); |
| 30 | + CREATE INDEX IF NOT EXISTS idx_bot_memory_user_chan_time ON bot_memory(user_id, channel_id, created_at DESC); |
| 31 | + CREATE INDEX IF NOT EXISTS idx_bot_memory_user_time ON bot_memory(user_id, created_at DESC); |
| 32 | + """ |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +def ensure_store() -> None: |
| 37 | + async def run(): |
| 38 | + conn = await asyncpg.connect(_dsn()) |
| 39 | + try: |
| 40 | + await _ensure_async(conn) |
| 41 | + finally: |
| 42 | + await conn.close() |
| 43 | + |
| 44 | + asyncio.run(run()) |
| 45 | + |
| 46 | + |
| 47 | +def save_message(*, user_id: int, guild_id: Optional[int], channel_id: Optional[int], role: str, content: str, kind: str = "message") -> None: |
| 48 | + async def run(): |
| 49 | + conn = await asyncpg.connect(_dsn()) |
| 50 | + try: |
| 51 | + await _ensure_async(conn) |
| 52 | + await conn.execute( |
| 53 | + """ |
| 54 | + INSERT INTO bot_memory(user_id, guild_id, channel_id, role, kind, content) |
| 55 | + VALUES ($1, $2, $3, $4, $5, $6) |
| 56 | + """, |
| 57 | + int(user_id), |
| 58 | + int(guild_id) if guild_id is not None else None, |
| 59 | + int(channel_id) if channel_id is not None else None, |
| 60 | + role, |
| 61 | + kind, |
| 62 | + content, |
| 63 | + ) |
| 64 | + finally: |
| 65 | + await conn.close() |
| 66 | + |
| 67 | + asyncio.run(run()) |
| 68 | + |
| 69 | + |
| 70 | +@dataclass |
| 71 | +class MemorySlice: |
| 72 | + summary: Optional[str] |
| 73 | + recent: list[tuple[str, str]] # list of (role, content) |
| 74 | + |
| 75 | + |
| 76 | +def load_slice(*, user_id: int, channel_id: Optional[int], limit: int = 8) -> MemorySlice: |
| 77 | + async def run() -> MemorySlice: |
| 78 | + conn = await asyncpg.connect(_dsn()) |
| 79 | + try: |
| 80 | + await _ensure_async(conn) |
| 81 | + # summary (latest) |
| 82 | + row = await conn.fetchrow( |
| 83 | + """ |
| 84 | + SELECT content FROM bot_memory |
| 85 | + WHERE user_id=$1 AND role='summary' |
| 86 | + ORDER BY created_at DESC |
| 87 | + LIMIT 1 |
| 88 | + """, |
| 89 | + int(user_id), |
| 90 | + ) |
| 91 | + summary = str(row["content"]) if row and row["content"] else None |
| 92 | + |
| 93 | + # recent conversation in channel (user/assistant roles) |
| 94 | + if channel_id is not None: |
| 95 | + rows: Sequence[asyncpg.Record] = await conn.fetch( |
| 96 | + """ |
| 97 | + SELECT role, content FROM bot_memory |
| 98 | + WHERE user_id=$1 AND channel_id=$2 AND role IN ('user','assistant') |
| 99 | + ORDER BY created_at DESC |
| 100 | + LIMIT $3 |
| 101 | + """, |
| 102 | + int(user_id), |
| 103 | + int(channel_id), |
| 104 | + int(limit), |
| 105 | + ) |
| 106 | + else: |
| 107 | + rows = await conn.fetch( |
| 108 | + """ |
| 109 | + SELECT role, content FROM bot_memory |
| 110 | + WHERE user_id=$1 AND role IN ('user','assistant') |
| 111 | + ORDER BY created_at DESC |
| 112 | + LIMIT $2 |
| 113 | + """, |
| 114 | + int(user_id), |
| 115 | + int(limit), |
| 116 | + ) |
| 117 | + recent = [(str(r["role"]), str(r["content"])) for r in rows] |
| 118 | + recent.reverse() # chronological |
| 119 | + return MemorySlice(summary=summary, recent=list(recent)) |
| 120 | + finally: |
| 121 | + await conn.close() |
| 122 | + |
| 123 | + return asyncio.run(run()) |
| 124 | + |
| 125 | + |
| 126 | +def update_summary_with_ai(*, current_summary: Optional[str], user_text: str, bot_answer: str, answer_llm: callable) -> Optional[str]: |
| 127 | + """Use the LLM to keep a concise user memory summary. |
| 128 | +
|
| 129 | + answer_llm: callable(question: str, system_prompt: Optional[str]) -> str |
| 130 | + """ |
| 131 | + sys_prompt = ( |
| 132 | + "Du bist ein Assistent, der eine kurze, stichpunktartige Nutzer-Zusammenfassung pflegt.\n" |
| 133 | + "Extrahiere nur langlebige Fakten, Präferenzen, Schreibstil/Emoji-Vorlieben, Sprache, wichtige Kontexte.\n" |
| 134 | + "Halte es knapp (max. ~6 Stichpunkte), keine PII, nichts Sensibles. Aktualisiere konsistent.\n" |
| 135 | + ) |
| 136 | + base = current_summary or "(leer)" |
| 137 | + question = ( |
| 138 | + "Aktualisiere diese Nutzer-Zusammenfassung auf Basis der neuen Interaktion.\n\n" |
| 139 | + f"Bisherige Zusammenfassung:\n{base}\n\n" |
| 140 | + f"Neue Nachricht des Nutzers:\n{user_text}\n\n" |
| 141 | + f"Antwort des Bots:\n{bot_answer}" |
| 142 | + ) |
| 143 | + try: |
| 144 | + updated = answer_llm(question, system_prompt=sys_prompt) |
| 145 | + return updated.strip() |
| 146 | + except Exception: |
| 147 | + return None |
| 148 | + |
0 commit comments