232 lines
10 KiB
Swift
232 lines
10 KiB
Swift
import Foundation
|
|
import SQLite3
|
|
|
|
struct Conversation: Identifiable {
|
|
let id: UUID
|
|
let title: String
|
|
}
|
|
|
|
final class Store {
|
|
private let db: OpaquePointer
|
|
private let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
|
|
|
|
init(url: URL) throws {
|
|
var connection: OpaquePointer?
|
|
let status = sqlite3_open_v2(url.path, &connection, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil)
|
|
guard status == SQLITE_OK, let connection else {
|
|
if let connection { sqlite3_close(connection) }
|
|
throw StudioError("Could not open the chat database.")
|
|
}
|
|
db = connection
|
|
sqlite3_busy_timeout(db, 3000)
|
|
try execute("PRAGMA foreign_keys = ON")
|
|
try execute("""
|
|
CREATE TABLE IF NOT EXISTS chats(
|
|
id TEXT PRIMARY KEY, title TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS messages(
|
|
id TEXT PRIMARY KEY, chat TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
|
role TEXT NOT NULL, content TEXT NOT NULL, thinking TEXT NOT NULL, backend TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS messages_chat ON messages(chat);
|
|
CREATE TABLE IF NOT EXISTS documents(
|
|
id TEXT PRIMARY KEY, chat TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
|
title TEXT NOT NULL
|
|
);
|
|
CREATE VIRTUAL TABLE IF NOT EXISTS document_index USING fts5(
|
|
document UNINDEXED, content, tokenize='unicode61'
|
|
);
|
|
CREATE TABLE IF NOT EXISTS document_vectors(
|
|
chunk INTEGER PRIMARY KEY, document TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
|
language TEXT NOT NULL, vector TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS document_vectors_document ON document_vectors(document, language);
|
|
CREATE TRIGGER IF NOT EXISTS documents_delete AFTER DELETE ON documents BEGIN
|
|
DELETE FROM document_index WHERE document=old.id;
|
|
END;
|
|
""")
|
|
}
|
|
|
|
deinit { sqlite3_close(db) }
|
|
|
|
func conversations() throws -> [Conversation] {
|
|
try query("SELECT id,title FROM chats ORDER BY rowid DESC") {
|
|
Conversation(id: try uuid($0, 0), title: string($0, 1))
|
|
}
|
|
}
|
|
|
|
func searchConversations(_ term: String) throws -> [Conversation] {
|
|
let term = term.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !term.isEmpty else { return try conversations() }
|
|
return try query("""
|
|
SELECT c.id, c.title FROM chats c
|
|
WHERE instr(lower(c.title), lower(?)) > 0 OR EXISTS (
|
|
SELECT 1 FROM messages m WHERE m.chat=c.id AND instr(lower(m.content), lower(?)) > 0
|
|
)
|
|
ORDER BY c.rowid DESC
|
|
""", [term, term]) {
|
|
Conversation(id: try uuid($0, 0), title: string($0, 1))
|
|
}
|
|
}
|
|
|
|
func rename(_ id: UUID, title: String) throws {
|
|
try mutate("UPDATE chats SET title=? WHERE id=?", [title, id.uuidString])
|
|
}
|
|
|
|
func create(title: String) throws -> Conversation {
|
|
let chat = Conversation(id: UUID(), title: title)
|
|
try mutate("INSERT INTO chats(id,title) VALUES(?,?)", [chat.id.uuidString, title])
|
|
return chat
|
|
}
|
|
|
|
func delete(_ id: UUID) throws {
|
|
try mutate("DELETE FROM chats WHERE id=?", [id.uuidString])
|
|
}
|
|
|
|
func save(_ message: Message, in chat: UUID) throws {
|
|
try mutate("INSERT INTO messages(id,chat,role,content,thinking,backend) VALUES(?,?,?,?,?,?)",
|
|
[message.id.uuidString, chat.uuidString, message.role.rawValue, message.content, message.thinking, message.backend])
|
|
}
|
|
|
|
func messages(in chat: UUID) throws -> [Message] {
|
|
try query("SELECT id,role,content,thinking,backend FROM messages WHERE chat=? ORDER BY rowid",
|
|
[chat.uuidString]) { row in
|
|
guard let role = Role(rawValue: string(row, 1)) else { throw StudioError("Invalid stored message role.") }
|
|
return Message(id: try uuid(row, 0), role: role, content: string(row, 2),
|
|
thinking: string(row, 3), backend: string(row, 4))
|
|
}
|
|
}
|
|
|
|
func memory(matching prompt: String, in chat: UUID, excluding: Set<UUID> = []) throws -> [String] {
|
|
let terms = Array(Set(prompt.lowercased().split { !$0.isLetter && !$0.isNumber }
|
|
.filter { $0.count >= 4 }.prefix(12).map(String.init))).sorted()
|
|
guard !terms.isEmpty else { return [] }
|
|
let termsSQL = Array(repeating: "instr(lower(content), ?) > 0", count: terms.count).joined(separator: " OR ")
|
|
let excluded = excluding.map(\.uuidString).sorted()
|
|
let exclusion = excluded.isEmpty ? "" :
|
|
" AND id NOT IN (" + Array(repeating: "?", count: excluded.count).joined(separator: ",") + ")"
|
|
return try query("""
|
|
SELECT substr(content,1,1200) FROM messages
|
|
WHERE chat=? AND role='user' AND (\(termsSQL))\(exclusion)
|
|
ORDER BY rowid DESC LIMIT 4
|
|
""", [chat.uuidString] + terms + excluded) { string($0, 0) }
|
|
}
|
|
|
|
func documents(in chat: UUID) throws -> [LibraryDocument] {
|
|
try query("SELECT id,title FROM documents WHERE chat=? ORDER BY rowid DESC", [chat.uuidString]) {
|
|
LibraryDocument(id: try uuid($0, 0), title: string($0, 1))
|
|
}
|
|
}
|
|
|
|
func addDocument(title: String, chunks: [String], vectors: [DocumentVector?] = [], in chat: UUID) throws {
|
|
let id = UUID().uuidString
|
|
try execute("BEGIN IMMEDIATE")
|
|
do {
|
|
try mutate("INSERT INTO documents(id,chat,title) VALUES(?,?,?)", [id, chat.uuidString, title])
|
|
for (index, chunk) in chunks.enumerated() {
|
|
try mutate("INSERT INTO document_index(document,content) VALUES(?,?)", [id, chunk])
|
|
if vectors.indices.contains(index), let vector = vectors[index] {
|
|
let row = String(sqlite3_last_insert_rowid(db))
|
|
try mutate("INSERT INTO document_vectors(chunk,document,language,vector) VALUES(?,?,?,?)",
|
|
[row, id, vector.language, vector.encoded])
|
|
}
|
|
}
|
|
try execute("COMMIT")
|
|
} catch {
|
|
try? execute("ROLLBACK")
|
|
throw error
|
|
}
|
|
}
|
|
|
|
func deleteDocument(_ id: UUID, in chat: UUID) throws {
|
|
try mutate("DELETE FROM documents WHERE id=? AND chat=?", [id.uuidString, chat.uuidString])
|
|
}
|
|
|
|
func excerpts(matching prompt: String, in chat: UUID, vector: DocumentVector? = nil) throws -> [DocumentExcerpt] {
|
|
let match = LibraryImport.matchQuery(prompt)
|
|
let lexical: [DocumentExcerpt]
|
|
if match.isEmpty {
|
|
lexical = []
|
|
} else {
|
|
lexical = try query("""
|
|
SELECT d.title, substr(i.content,1,1600)
|
|
FROM document_index i JOIN documents d ON d.id=i.document
|
|
WHERE document_index MATCH ? AND d.chat=?
|
|
ORDER BY i.rank LIMIT 4
|
|
""", [match, chat.uuidString]) {
|
|
DocumentExcerpt(title: string($0, 0), text: string($0, 1))
|
|
}
|
|
}
|
|
guard let vector else { return lexical }
|
|
let candidates: [(score: Float, id: String)] = try query("""
|
|
SELECT v.chunk, v.vector FROM document_vectors v
|
|
JOIN documents d ON d.id=v.document WHERE d.chat=? AND v.language=?
|
|
ORDER BY v.chunk DESC LIMIT 3000
|
|
""", [chat.uuidString, vector.language]) { row in
|
|
(vector.similarity(to: string(row, 1)) ?? -1, string(row, 0))
|
|
}
|
|
var excerpts = Array(lexical.prefix(2))
|
|
for candidate in candidates.sorted(by: { $0.score > $1.score }).prefix(8) where candidate.score >= 0.35 {
|
|
let matches = try query("""
|
|
SELECT d.title, substr(i.content,1,1600)
|
|
FROM document_index i JOIN documents d ON d.id=i.document WHERE i.rowid=? AND d.chat=?
|
|
""", [candidate.id, chat.uuidString]) { row in
|
|
DocumentExcerpt(title: string(row, 0), text: string(row, 1))
|
|
}
|
|
if let excerpt = matches.first, !excerpts.contains(excerpt) { excerpts.append(excerpt) }
|
|
if excerpts.count == 4 { return excerpts }
|
|
}
|
|
for excerpt in lexical where excerpts.count < 4 && !excerpts.contains(excerpt) { excerpts.append(excerpt) }
|
|
return excerpts
|
|
}
|
|
|
|
private func execute(_ sql: String) throws {
|
|
guard sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK else { throw failure }
|
|
}
|
|
|
|
private func mutate(_ sql: String, _ values: [String]) throws {
|
|
try statement(sql, values) {
|
|
guard sqlite3_step($0) == SQLITE_DONE else { throw failure }
|
|
}
|
|
}
|
|
|
|
private func query<T>(_ sql: String, _ values: [String] = [], map: (OpaquePointer) throws -> T) throws -> [T] {
|
|
try statement(sql, values) { statement in
|
|
var rows: [T] = []
|
|
while true {
|
|
switch sqlite3_step(statement) {
|
|
case SQLITE_ROW: rows.append(try map(statement))
|
|
case SQLITE_DONE: return rows
|
|
default: throw failure
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func statement<T>(_ sql: String, _ values: [String], run: (OpaquePointer) throws -> T) throws -> T {
|
|
var handle: OpaquePointer?
|
|
guard sqlite3_prepare_v2(db, sql, -1, &handle, nil) == SQLITE_OK, let handle else { throw failure }
|
|
defer { sqlite3_finalize(handle) }
|
|
for (index, value) in values.enumerated() {
|
|
let result = value.withCString {
|
|
sqlite3_bind_text(handle, Int32(index + 1), $0, Int32(value.utf8.count), transient)
|
|
}
|
|
guard result == SQLITE_OK else { throw failure }
|
|
}
|
|
return try run(handle)
|
|
}
|
|
|
|
private func uuid(_ row: OpaquePointer, _ column: Int32) throws -> UUID {
|
|
guard let id = UUID(uuidString: string(row, column)) else { throw StudioError("Invalid stored ID.") }
|
|
return id
|
|
}
|
|
|
|
private func string(_ row: OpaquePointer, _ column: Int32) -> String {
|
|
guard let text = sqlite3_column_text(row, column) else { return "" }
|
|
let count = Int(sqlite3_column_bytes(row, column))
|
|
return String(decoding: UnsafeBufferPointer(start: text, count: count), as: UTF8.self)
|
|
}
|
|
|
|
private var failure: StudioError { StudioError(String(cString: sqlite3_errmsg(db))) }
|
|
}
|