-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_setup.py
More file actions
126 lines (107 loc) · 3.53 KB
/
Copy pathmemory_setup.py
File metadata and controls
126 lines (107 loc) · 3.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""
Hermes memory setup for self-hosted llama.cpp.
Assumes llama-server is running on 127.0.0.1:8080 with --embedding enabled.
"""
import os
import sqlite3
import requests
LLAMA_HOST = os.environ.get("LLAMA_HOST", "http://127.0.0.1:8080")
EMBED_MODEL = os.environ.get("LLAMA_EMBED_MODEL", "qwen2.5-7b-instruct-q4_k_m")
DB_PATH = os.environ.get("MEMORY_DB", "/opt/hermes/data/memory.sqlite3")
def init_db():
db_dir = os.path.dirname(DB_PATH)
if db_dir:
os.makedirs(db_dir, exist_ok=True)
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT,
role TEXT,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS tickets (
ticket_id TEXT PRIMARY KEY,
user_id TEXT,
status TEXT,
subject TEXT,
body TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
def add_message(user_id: str, role: str, content: str):
conn = sqlite3.connect(DB_PATH)
conn.execute(
"INSERT INTO messages(user_id, role, content) VALUES (?, ?, ?)",
(user_id, role, content),
)
conn.commit()
conn.close()
def get_recent_messages(user_id: str, limit: int = 20):
conn = sqlite3.connect(DB_PATH)
cur = conn.execute(
"SELECT role, content, created_at FROM messages WHERE user_id = ? ORDER BY id DESC LIMIT ?",
(user_id, limit),
)
rows = cur.fetchall()
conn.close()
return list(reversed(rows))
def embed(text: str) -> list[float]:
try:
r = requests.post(
f"{LLAMA_HOST}/embedding",
json={"content": text, "model": EMBED_MODEL},
timeout=60,
)
r.raise_for_status()
data = r.json()
if "embedding" in data:
return data["embedding"]
if "data" in data and data["data"]:
return data["data"][0]["embedding"]
raise ValueError(f"Unexpected embedding response: {data}")
except Exception as e:
raise RuntimeError(f"Embedding failed: {e}")
def create_ticket(ticket_id: str, user_id: str, subject: str, body: str, status: str = "open"):
conn = sqlite3.connect(DB_PATH)
conn.execute(
"INSERT OR REPLACE INTO tickets(ticket_id, user_id, status, subject, body) VALUES (?, ?, ?, ?, ?)",
(ticket_id, user_id, status, subject, body),
)
conn.commit()
conn.close()
def update_ticket_status(ticket_id: str, status: str):
conn = sqlite3.connect(DB_PATH)
conn.execute(
"UPDATE tickets SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE ticket_id = ?",
(status, ticket_id),
)
conn.commit()
conn.close()
def search_tickets(user_id: str, query: str, limit: int = 10):
conn = sqlite3.connect(DB_PATH)
cur = conn.execute(
"""
SELECT ticket_id, subject, body, status, created_at
FROM tickets
WHERE user_id = ? AND (subject LIKE ? OR body LIKE ?)
ORDER BY created_at DESC
LIMIT ?
""",
(user_id, f"%{query}%", f"%{query}%", limit),
)
rows = cur.fetchall()
conn.close()
return rows
if __name__ == "__main__":
init_db()
print("memory DB initialized at", DB_PATH)
test = embed("ping")
print("embedding OK, dim=", len(test))