+# =====================================================================
+# --- BACKGROUND MEMORY SUMMARIZER (The "Dream State") ---
+# =====================================================================
+async def memory_summarizer_worker(session):
+ print("[BACKGROUND] Memory Summarizer Worker is active.")
+ while True:
+ job = await memory_queue.get()
+ session_id = job['session_id']
+ player_name = job['player_name']
+ npc_tag = job['npc_tag']
+ chat_log = job['chat_log']
+
+ prompt = f"Summarize the key events, facts, and the emotional tone of this conversation snippet between {player_name} and {npc_tag}. Keep it to 2 brief sentences in the past tense.\nConversation Log:\n{chat_log}"
+
+ try:
+ print(f"[MEMORY DB] Generating background memory for {player_name} and {npc_tag}...")
+ # We use /api/generate here because we just want a raw text summary, not a JSON macro
+ async with session.post('http://localhost:11434/api/generate', json={
+ "model": "gemma4",
+ "prompt": prompt,
+ "stream": False,
+ "options": {
+ "temperature": 0.1
+ }
+ }) as response:
+ result = await response.json()
+ summary = result['response'].strip()
+
+ if summary:
+ doc_id = f"{session_id}_{int(time.time())}"
+ # We store the session_id as metadata so NPCs only recall their OWN memories with this specific player
+ memory_collection.add(
+ documents=[summary],
+ metadatas=[{"session_id": session_id}],
+ ids=[doc_id]
+ )
+ print(f"[MEMORY DB] Memory Saved: {summary}")
+
+ except Exception as e:
+ print(f"[MEMORY ERROR] Failed to summarize memory: {e}")
+
+ memory_queue.task_done()
+# =====================================================================
+
+