-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
66 lines (58 loc) · 2.24 KB
/
Copy pathdb.py
File metadata and controls
66 lines (58 loc) · 2.24 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
# ============================== #
# Database Module #
# ============================== #
# --- Imports ---
import aiosqlite
import os
from dotenv import load_dotenv
# --- Load Environment Variables ---
load_dotenv()
DB_NAME = os.getenv("USER_CONTEXT") # SQLite DB filename from .env
# --- Persistent DB Connection ---
_db_connection = None # Global connection to avoid repeated opening
# --- Initialize DB (Create Table + Index) ---
async def initialize():
global _db_connection
if _db_connection is None:
_db_connection = await aiosqlite.connect(DB_NAME)
await _db_connection.execute("""
CREATE TABLE IF NOT EXISTS user_responses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
prompt TEXT NOT NULL,
response TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
""")
# Index for fast lookup by user and time
await _db_connection.execute(
"CREATE INDEX IF NOT EXISTS idx_user_time ON user_responses(user_id, timestamp);"
)
await _db_connection.commit()
# --- Store a User's Prompt + Response ---
async def store_user_response(user_id: int, prompt: str, response: str):
await _db_connection.execute(
"INSERT INTO user_responses (user_id, prompt, response) VALUES (?, ?, ?)",
(user_id, prompt, response)
)
await _db_connection.commit()
# --- Fetch User History (Truncate to max_chars) ---
async def get_user_history(user_id: int, max_chars: int = 150000):
"""
Returns a list of Q&A strings for a user, capped by total character length.
Newest entries are included first, but returned oldest-first for prompt building.
"""
async with _db_connection.execute(
"SELECT prompt, response FROM user_responses WHERE user_id = ? ORDER BY timestamp DESC",
(user_id,)
) as cursor:
rows = await cursor.fetchall()
history = []
total_len = 0
for prompt, response in reversed(rows): # oldest to newest
entry = f"Q: {prompt}\nA: {response}\n"
total_len += len(entry)
if total_len > max_chars:
break
history.append(entry)
return history