]> vgcfreebox.myrthtech.pt Git - alentejosemlei.git/blob - redis_bridge.py
bc40dfab6d461f4d7b05102d14a7a70a93b7348e
[alentejosemlei.git] / redis_bridge.py
1 import redis
2 import json
3 import requests
4
5 print("Initializing Redis Bridge...")
6
7 # 1. Force the correct Windows IP address and test the connection immediately
8 try:
9 r = redis.Redis(host='127.0.0.1', port=6380, decode_responses=True)
10 r.ping() # This will crash immediately if the connection is bad
11 print("SUCCESS: Connected to the Docker Redis database!")
12 except Exception as e:
13 print(f"CRITICAL ERROR: Could not connect to Redis. {e}")
14 exit()
15
16 NPC_SYSTEM_PROMPT = """
17 You are Elrendur Arna. You are currently residing in Alentejo Sem Lei.
18 Keep your responses under 3 sentences.
19 """
20 chat_history = [{"role": "system", "content": NPC_SYSTEM_PROMPT}]
21
22 print("\nReady! Listening for game messages on 'nwn_to_llm'...")
23
24 while True:
25 try:
26 # This line freezes the script until a message arrives
27 result = r.blpop('nwn_to_llm')
28
29 # --- IF IT HEARS THE GAME, IT WILL PRINT THIS ---
30 print(f"\n--- WAKE UP! NEW MESSAGE RECEIVED ---")
31
32 queue_name, message_data = result
33 print(f"Raw data from Redis: {message_data}")
34
35 # Try to parse the JSON
36 data = json.loads(message_data)
37 player_name = data.get('player', 'Unknown')
38 npc_tag = data.get('npc_tag', 'UnknownNPC')
39 message = data.get('message', '')
40
41 print(f"Parsed: {player_name} said to {npc_tag}: '{message}'")
42
43 chat_history.append({"role": "user", "content": f"{player_name} says: {message}"})
44
45 # Talk to Ollama
46 print("Thinking... (Sending to local Ollama)")
47 response = requests.post('http://localhost:11434/api/chat', json={
48 "model": "llama3",
49 "messages": chat_history,
50 "stream": False
51 }, timeout=45)
52
53 response.raise_for_status() # Triggers an error if Ollama is broken
54 reply_text = response.json()['message']['content']
55
56 print(f"Ollama Replied: {reply_text}")
57 chat_history.append({"role": "assistant", "content": reply_text})
58
59 # Package and send back to the game
60 reply_payload = {
61 "player": player_name,
62 "npc_tag": npc_tag,
63 "reply": reply_text
64 }
65
66 r.rpush('llm_to_nwn', json.dumps(reply_payload))
67 print("SUCCESS: Sent reply to the 'llm_to_nwn' queue for the game to pick up!")
68
69 except json.JSONDecodeError as e:
70 print(f"ERROR: The game sent bad JSON data: {e}")
71 except requests.exceptions.RequestException as e:
72 print(f"ERROR: Failed to talk to Ollama. Is it running? {e}")
73 except Exception as e:
74 print(f"UNEXPECTED ERROR: {e}")