-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
90 lines (71 loc) · 2.92 KB
/
main.py
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
import ollama, sqlite3, sys, os, time
os.system('cls' if os.name == 'nt' else 'clear')
if len(sys.argv) < 2:
print("Missing argument: SQLite database path\neg: python main.py path/to/database.db")
exit(1)
database = sys.argv[1]
contents = []
messages = []
def get_tables(database):
with sqlite3.connect(database) as conn:
with conn:
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
return tables
def get_data(database, table):
with sqlite3.connect(database) as conn:
with conn:
cursor = conn.execute("SELECT * FROM " + table[0] + ";")
data = cursor.fetchall()
return data
def get_schema(database, table):
with sqlite3.connect(database) as conn:
with conn:
cursor = conn.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='" + table[0] + "';")
schema = cursor.fetchall()
return schema
def prompt_ai(prompt, contents, messages):
messages.append({"role": "user", "content": f"prompt: {prompt}\ncontent: {contents}"})
duration = time.time()
print("----\nRESPONSE:")
response = ollama.chat(
model='llama3.1',
messages= messages,
stream= True
)
full_response = ""
for chunk in response:
content = chunk['message']['content']
print(content, end='', flush=True)
full_response += content
return full_response
if __name__ == "__main__":
try:
tables = get_tables(database)
print(f"Loading database: {database}")
messages= [
{"role": "system", "content": """
You are an assistant that responds to user inquiries regarding their own SQLite3 databases.
You are given a prompt, and content - which contains the schema and data of the database.
Do not hallucinate. Keep it natural, concise, and relevant to the prompt. Do not explain unless asked to, have a conversation with the user.
Do not include any code.
Your output must only be plain text, no markdown or rich text formatting - no bolding or italic, unless the user specified you to.
"""},
]
num = 0
for table in tables:
num += 1
schema = get_schema(database, table)
data = get_data(database, table)
contents.append({"schema": schema, "data": data})
print(f"{num}/{len(tables)} Loaded table '{table[0]}'")
summary = prompt_ai(f"Hello! Suggest what actions can be done with the database {database}, start by asking the user what the database is about", contents, messages)
while True:
prompt = input("\n---------\nPROMPT: ")
if prompt == "exit":
exit()
else:
response = prompt_ai(prompt, contents, messages)
except sqlite3.OperationalError:
print("Invalid database path")
exit(1)