+ if session_id not in chat_memory:
+ chat_memory[session_id] = [{"role": "system", "content": dynamic_system_prompt}]
+
+ chat_memory[session_id].append({"role": "user", "content": f"{player_name} says: {message}"})
+
+ # Sliding Window Fix
+ # Remember the System Prompt [0] + the last 4 messages [-4:]
+ if len(chat_memory[session_id]) > 10:
+ chat_memory[session_id] = [chat_memory[session_id][0]] + chat_memory[session_id][-5:]
+
+ async with semaphore:
+ print(f"[THINKING] Processing reply for {player_name}...")
+ async with session.post('http://localhost:11434/api/chat', json={
+ "model": "llama3",
+ #"model": "qwen2.5:3b",
+ "messages": chat_memory[session_id],
+ "format": "json",
+ "stream": False,
+ "options": {
+ "temperature": 0.2
+ #"num_predict": 120
+ }
+ }, timeout=45) as response:
+
+ response.raise_for_status()
+ result = await response.json()
+ raw_reply_text = result['message']['content']
+
+ # =====================================================================
+ # THE PYTHON BOUNCER (Sanitization)
+ # =====================================================================
+ try:
+ agent_brain = json.loads(raw_reply_text)
+ agent_brain = {k.lower(): v for k, v in agent_brain.items()}
+
+ # Ensure all 5 keys exist
+ if "thought" not in agent_brain: agent_brain["thought"] = ""
+ if "speech" not in agent_brain: agent_brain["speech"] = ""
+ if "emotion" not in agent_brain: agent_brain["emotion"] = "NEUTRAL"
+ if "action" not in agent_brain: agent_brain["action"] = "GUARD"
+ if "action_target" not in agent_brain: agent_brain["action_target"] = ""
+
+ # --- THE NEW ANTI-SILENCE & TARGET CLEANUP FIXES ---
+ if not agent_brain["speech"].strip():
+ agent_brain["speech"] = "*grunts quietly*"
+
+ agent_brain["action_target"] = agent_brain["action_target"].replace("?", "").replace(".", "").strip()
+ # ---------------------------------------------------
+
+ clean_reply_text = json.dumps(agent_brain)
+
+ except json.JSONDecodeError:
+ print(f"[WARNING] AI Hallucinated! Overriding with safe defaults.")
+ clean_reply_text = json.dumps({
+ "thought": "I lost my train of thought.",
+ "speech": "*grunts quietly*",
+ "emotion": "NEUTRAL",
+ "action": "WANDER",
+ "action_target": ""
+ })
+ # =====================================================================
+
+ print(f"[REPLY] from {npc_tag} to {player_name}: {clean_reply_text}")
+ chat_memory[session_id].append({"role": "assistant", "content": clean_reply_text})