· 5 months ago · Apr 17, 2025, 01:05 PM
1## FILENAME: ai_memory.py
2## Use this in conjunctin with my main.py for open-webui
3##
4import sqlite3
5import os
6
7# Path to the SQLite database
8DB_PATH = os.path.join(os.path.dirname(__file__), "memory.db")
9
10# Connect to the database (or create it)
11def connect_db():
12 conn = sqlite3.connect(DB_PATH)
13 conn.row_factory = sqlite3.Row
14 return conn
15
16# Initialize database and tables
17def init_db():
18 conn = connect_db()
19 cursor = conn.cursor()
20
21 # Table to store people (names, facts)
22 cursor.execute('''
23 CREATE TABLE IF NOT EXISTS people (
24 id INTEGER PRIMARY KEY AUTOINCREMENT,
25 name TEXT NOT NULL,
26 info TEXT
27 )
28 ''')
29
30 # Table to store conversations
31 cursor.execute('''
32 CREATE TABLE IF NOT EXISTS conversations (
33 id INTEGER PRIMARY KEY AUTOINCREMENT,
34 user_input TEXT,
35 ai_response TEXT,
36 timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
37 )
38 ''')
39
40 # Table to store memory facts
41 cursor.execute('''
42 CREATE TABLE IF NOT EXISTS memory_facts (
43 id INTEGER PRIMARY KEY AUTOINCREMENT,
44 subject TEXT,
45 fact TEXT
46 )
47 ''')
48
49 conn.commit()
50 conn.close()
51
52# Save a conversation turn
53def save_conversation(user_input, ai_response):
54 conn = connect_db()
55 cursor = conn.cursor()
56 cursor.execute('''
57 INSERT INTO conversations (user_input, ai_response)
58 VALUES (?, ?)
59 ''', (user_input, ai_response))
60 conn.commit()
61 conn.close()
62
63# Save or update a memory fact
64def save_fact(subject, fact):
65 conn = connect_db()
66 cursor = conn.cursor()
67 cursor.execute('DELETE FROM memory_facts WHERE subject = ?', (subject,))
68 cursor.execute('INSERT INTO memory_facts (subject, fact) VALUES (?, ?)', (subject, fact))
69 conn.commit()
70 conn.close()
71
72# Get all memory facts
73def get_facts():
74 conn = connect_db()
75 cursor = conn.cursor()
76 cursor.execute('SELECT subject, fact FROM memory_facts')
77 rows = cursor.fetchall()
78 conn.close()
79 return {row['subject']: row['fact'] for row in rows}
80
81# Save a person of importance
82def save_person(name, info):
83 conn = connect_db()
84 cursor = conn.cursor()
85 cursor.execute('INSERT INTO people (name, info) VALUES (?, ?)', (name, info))
86 conn.commit()
87 conn.close()
88
89# Retrieve all saved people
90def get_people():
91 conn = connect_db()
92 cursor = conn.cursor()
93 cursor.execute('SELECT name, info FROM people')
94 rows = cursor.fetchall()
95 conn.close()
96 return {row['name']: row['info'] for row in rows}
97
98# Call this once at startup
99def initialize():
100 init_db()
101