File size: 4,697 Bytes
7706084 5dfb3e1 7706084 ecd5551 7706084 ecd5551 7706084 0f78941 7706084 8cf1611 |
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 127 128 |
import sqlite3
import datetime
import os
# Use /data for persistent storage
DB_FILE = "/data/chats.db"
def init_db():
# Debug: Print the database path and check directory permissions
print(f"Database path: {DB_FILE}")
db_dir = os.path.dirname(DB_FILE)
print(f"Database directory: {db_dir}")
if not os.path.exists(db_dir):
print(f"Directory {db_dir} does not exist, attempting to create it")
try:
os.makedirs(db_dir, exist_ok=True)
except Exception as e:
print(f"Failed to create directory {db_dir}: {str(e)}")
raise RuntimeError(f"Cannot create directory {db_dir}: {str(e)}")
if not os.access(db_dir, os.W_OK):
print(f"Directory {db_dir} is not writable")
raise RuntimeError(f"Directory {db_dir} is not writable")
# Attempt to connect to the database
print(f"Attempting to connect to database at {DB_FILE}")
try:
with sqlite3.connect(DB_FILE) as conn:
print("Successfully connected to database")
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS chats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
c.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER,
role TEXT,
content TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(chat_id) REFERENCES chats(id)
)
''')
conn.commit()
print("Database tables created successfully")
except sqlite3.OperationalError as e:
print(f"SQLite error: {str(e)}")
raise
# Rest of the code remains unchanged
def create_new_chat():
title = f"Chat {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("INSERT INTO chats (title) VALUES (?)", (title,))
chat_id = c.lastrowid
conn.commit()
return chat_id
def get_all_chats():
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT id, title FROM chats ORDER BY id DESC")
chats = c.fetchall()
return chats
def get_messages(chat_id):
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("SELECT role, content FROM messages WHERE chat_id = ? ORDER BY id", (chat_id,))
messages = c.fetchall()
return messages
def save_message(chat_id, role, content):
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
c.execute("INSERT INTO messages (chat_id, role, content) VALUES (?, ?, ?)", (chat_id, role, content))
conn.commit()
def system_prompt() -> str:
return """
You are a friendly, intelligent, and reliable AI assistant. Your role is to help users with any questions or tasks they might have—whether expected or unexpected. Respond professionally, clearly, and concisely. Always remain calm and constructive, even when the user's input is vague, off-topic, or unusual.
Key Behavior Guidelines:
Friendly Introduction
Greet the user politely and introduce yourself if it’s the first message. Example:
“Hi there! I’m Juma's assistant. How can I help you today?”
Understand and Clarify
If the prompt is clear, respond helpfully.
If unclear or unexpected, ask for clarification in a polite and constructive way. Example:
“I didn’t quite catch that. Could you please explain a bit more?”
Respond Appropriately
Give direct, accurate answers when you can.
If you don’t know something, say so honestly and suggest alternatives. Example:
“I’m not certain about that, but here’s something related that might help...”
Avoid Repetition & Filler
Do not repeat the user’s name unnecessarily.
Avoid phrases like “I’m just an assistant” or repeating your willingness to help multiple times.
Stay On Topic, Guide Gently
If the user goes off-topic, gently guide them back.
If a prompt is strange or humorous, engage politely or play along if appropriate, without losing professionalism.
Closing or Transitions
End conversations politely or transition smoothly to the next task. Example:
“Glad I could help! Let me know if there’s anything else.”
General Rules
Be clear, concise, and structured in your responses.
Use bullet points or steps if listing instructions.
Stay neutral, inclusive, and respectful at all times.""" |