new features
This commit is contained in:
+102
-48
@@ -22,6 +22,7 @@ struct WorkspaceSnippet: Identifiable {
|
||||
let content: String
|
||||
var notes = ""
|
||||
var tags = ""
|
||||
var examples: [PromptExample] = []
|
||||
}
|
||||
|
||||
struct PromptVersion: Identifiable {
|
||||
@@ -31,6 +32,7 @@ struct PromptVersion: Identifiable {
|
||||
let content: String
|
||||
let notes: String
|
||||
let tags: String
|
||||
var examples: [PromptExample] = []
|
||||
}
|
||||
|
||||
final class Store {
|
||||
@@ -79,10 +81,10 @@ final class Store {
|
||||
END;
|
||||
""")
|
||||
try preparePromptLibrary()
|
||||
try prepareWebSources()
|
||||
try prepareMessageSources()
|
||||
}
|
||||
|
||||
private func prepareWebSources() throws {
|
||||
private func prepareMessageSources() throws {
|
||||
try execute("""
|
||||
CREATE TABLE IF NOT EXISTS message_web_sources (
|
||||
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
||||
@@ -92,7 +94,10 @@ final class Store {
|
||||
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
||||
names TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS message_document_citations (
|
||||
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
||||
citations TEXT NOT NULL
|
||||
);
|
||||
""")
|
||||
}
|
||||
|
||||
@@ -107,6 +112,10 @@ final class Store {
|
||||
saved_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
title TEXT NOT NULL, content TEXT NOT NULL, notes TEXT NOT NULL, tags TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS prompt_version_examples (
|
||||
version TEXT PRIMARY KEY REFERENCES prompt_versions(id) ON DELETE CASCADE,
|
||||
examples TEXT NOT NULL
|
||||
);
|
||||
""")
|
||||
}
|
||||
|
||||
@@ -154,11 +163,18 @@ final class Store {
|
||||
}
|
||||
|
||||
func snippets() throws -> [WorkspaceSnippet] {
|
||||
try query("SELECT s.id,s.kind,s.title,s.content,m.notes,m.tags FROM workspace_snippets s LEFT JOIN prompt_metadata m ON m.prompt=s.id ORDER BY s.rowid DESC") {
|
||||
try query("""
|
||||
SELECT s.id,s.kind,s.title,s.content,m.notes,m.tags,
|
||||
(SELECT e.examples FROM prompt_versions v LEFT JOIN prompt_version_examples e ON e.version=v.id
|
||||
WHERE v.prompt=s.id ORDER BY v.rowid DESC LIMIT 1)
|
||||
FROM workspace_snippets s LEFT JOIN prompt_metadata m ON m.prompt=s.id ORDER BY s.rowid DESC
|
||||
""") {
|
||||
guard let kind = WorkspaceSnippet.Kind(rawValue: string($0, 1)) else {
|
||||
throw StudioError("Invalid workspace resource.")
|
||||
}
|
||||
return WorkspaceSnippet(id: try uuid($0, 0), kind: kind, title: string($0, 2), content: string($0, 3), notes: string($0, 4), tags: string($0, 5))
|
||||
return WorkspaceSnippet(id: try uuid($0, 0), kind: kind, title: string($0, 2),
|
||||
content: string($0, 3), notes: string($0, 4), tags: string($0, 5),
|
||||
examples: decodeArray(string($0, 6)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,13 +186,19 @@ final class Store {
|
||||
}
|
||||
|
||||
func promptVersions(_ id: UUID) throws -> [PromptVersion] {
|
||||
try query("SELECT id,saved_at,title,content,notes,tags FROM prompt_versions WHERE prompt=? ORDER BY rowid DESC", [id.uuidString]) {
|
||||
try query("""
|
||||
SELECT v.id,v.saved_at,v.title,v.content,v.notes,v.tags,e.examples
|
||||
FROM prompt_versions v LEFT JOIN prompt_version_examples e ON e.version=v.id
|
||||
WHERE v.prompt=? ORDER BY v.rowid DESC
|
||||
""", [id.uuidString]) {
|
||||
PromptVersion(id: string($0, 0), savedAt: string($0, 1), title: string($0, 2),
|
||||
content: string($0, 3), notes: string($0, 4), tags: string($0, 5))
|
||||
content: string($0, 3), notes: string($0, 4), tags: string($0, 5),
|
||||
examples: decodeArray(string($0, 6)))
|
||||
}
|
||||
}
|
||||
|
||||
func savePrompt(id: UUID, title: String, content: String, notes: String, tags: String) throws {
|
||||
func savePrompt(id: UUID, title: String, content: String, notes: String, tags: String,
|
||||
examples: [PromptExample] = []) throws {
|
||||
try execute("BEGIN IMMEDIATE")
|
||||
do {
|
||||
try saveSnippet(id: id, kind: .prompt, title: title, content: content)
|
||||
@@ -184,9 +206,14 @@ final class Store {
|
||||
INSERT INTO prompt_metadata(prompt,notes,tags) VALUES(?,?,?)
|
||||
ON CONFLICT(prompt) DO UPDATE SET notes=excluded.notes, tags=excluded.tags
|
||||
""", [id.uuidString, notes, tags])
|
||||
let version = UUID().uuidString
|
||||
try mutate("""
|
||||
INSERT INTO prompt_versions(id,prompt,title,content,notes,tags) VALUES(?,?,?,?,?,?)
|
||||
""", [UUID().uuidString, id.uuidString, title, content, notes, tags])
|
||||
""", [version, id.uuidString, title, content, notes, tags])
|
||||
if !examples.isEmpty {
|
||||
try mutate("INSERT INTO prompt_version_examples(version,examples) VALUES(?,?)",
|
||||
[version, String(decoding: try JSONEncoder().encode(examples), as: UTF8.self)])
|
||||
}
|
||||
try execute("COMMIT")
|
||||
} catch {
|
||||
try? execute("ROLLBACK")
|
||||
@@ -218,7 +245,10 @@ final class Store {
|
||||
[message.id.uuidString, chat.uuidString, message.role.rawValue, message.content, message.thinking, message.backend])
|
||||
}
|
||||
|
||||
guard !message.webSources.isEmpty || !message.documentNames.isEmpty else { try insertMessage(); return }
|
||||
guard !message.webSources.isEmpty || !message.documentNames.isEmpty || !message.documentCitations.isEmpty else {
|
||||
try insertMessage()
|
||||
return
|
||||
}
|
||||
let encoder = JSONEncoder()
|
||||
try execute("SAVEPOINT save_message_sources")
|
||||
do {
|
||||
@@ -233,6 +263,11 @@ final class Store {
|
||||
try mutate("INSERT INTO message_documents(message,names) VALUES(?,?)",
|
||||
[message.id.uuidString, String(decoding: names, as: UTF8.self)])
|
||||
}
|
||||
if !message.documentCitations.isEmpty {
|
||||
let citations = try encoder.encode(message.documentCitations)
|
||||
try mutate("INSERT INTO message_document_citations(message,citations) VALUES(?,?)",
|
||||
[message.id.uuidString, String(decoding: citations, as: UTF8.self)])
|
||||
}
|
||||
try execute("RELEASE save_message_sources")
|
||||
} catch {
|
||||
try? execute("ROLLBACK TO save_message_sources")
|
||||
@@ -243,10 +278,11 @@ final class Store {
|
||||
|
||||
func messages(in chat: UUID) throws -> [Message] {
|
||||
try query("""
|
||||
SELECT m.id,m.role,m.content,m.thinking,m.backend,w.sources,d.names
|
||||
SELECT m.id,m.role,m.content,m.thinking,m.backend,w.sources,d.names,c.citations
|
||||
FROM messages m
|
||||
LEFT JOIN message_web_sources w ON w.message=m.id
|
||||
LEFT JOIN message_documents d ON d.message=m.id
|
||||
LEFT JOIN message_document_citations c ON c.message=m.id
|
||||
WHERE m.chat=? ORDER BY m.rowid
|
||||
""", [chat.uuidString]) { row in
|
||||
guard let role = Role(rawValue: string(row, 1)) else { throw StudioError("Invalid stored message role.") }
|
||||
@@ -254,7 +290,8 @@ final class Store {
|
||||
let sources = (try? decoder.decode([WebReplySource].self, from: Data(string(row, 5).utf8))) ?? []
|
||||
let documents = (try? decoder.decode([String].self, from: Data(string(row, 6).utf8))) ?? []
|
||||
return Message(id: try uuid(row, 0), role: role, content: string(row, 2),
|
||||
thinking: string(row, 3), backend: string(row, 4), webSources: sources, documentNames: documents)
|
||||
thinking: string(row, 3), backend: string(row, 4), webSources: sources, documentNames: documents,
|
||||
documentCitations: decodeArray(string(row, 7)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,15 +323,23 @@ final class Store {
|
||||
}
|
||||
}
|
||||
|
||||
func openingExcerpts(in chat: UUID) throws -> [DocumentExcerpt] {
|
||||
func openingExcerpts(in chat: UUID, includeLocations: Bool = false) throws -> [DocumentExcerpt] {
|
||||
try query("""
|
||||
SELECT d.title, substr((SELECT i.content FROM document_index i WHERE i.document=d.id
|
||||
ORDER BY i.rowid LIMIT 1),1,1600)
|
||||
FROM documents d WHERE d.chat=? ORDER BY d.rowid DESC LIMIT 4
|
||||
""", [chat.uuidString]) { DocumentExcerpt(title: string($0, 0), text: string($0, 1)) }
|
||||
SELECT d.title, substr(i.content,1,1600), d.id, i.rowid
|
||||
FROM documents d JOIN document_index i ON i.rowid=(
|
||||
SELECT rowid FROM document_index WHERE document=d.id ORDER BY rowid LIMIT 1
|
||||
)
|
||||
WHERE d.chat=? ORDER BY d.rowid DESC LIMIT 4
|
||||
""", [chat.uuidString]) { try documentExcerpt($0, includeLocation: includeLocations) }
|
||||
.filter { !$0.text.isEmpty }
|
||||
}
|
||||
|
||||
private func documentExcerpt(_ row: OpaquePointer, includeLocation: Bool) throws -> DocumentExcerpt {
|
||||
DocumentExcerpt(title: string(row, 0), text: string(row, 1),
|
||||
documentID: includeLocation ? try uuid(row, 2) : nil,
|
||||
chunkID: includeLocation ? sqlite3_column_int64(row, 3) : nil)
|
||||
}
|
||||
|
||||
func addDocument(title: String, chunks: [String], vectors: [DocumentVector?] = [], in chat: UUID) throws {
|
||||
let id = UUID().uuidString
|
||||
try execute("BEGIN IMMEDIATE")
|
||||
@@ -319,42 +364,47 @@ final class Store {
|
||||
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] {
|
||||
func excerpts(matching prompt: String, in chat: UUID, vector: DocumentVector? = nil,
|
||||
includeLocations: Bool = false) 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))
|
||||
let lexical: [Int64] = match.isEmpty ? [] : try query("""
|
||||
SELECT i.rowid FROM document_index i JOIN documents d ON d.id=i.document
|
||||
WHERE document_index MATCH ? AND d.chat=?
|
||||
ORDER BY i.rank, i.rowid LIMIT 24
|
||||
""", [match, chat.uuidString]) { sqlite3_column_int64($0, 0) }
|
||||
var semantic: [Int64] = []
|
||||
if let vector {
|
||||
let candidates: [(id: Int64, score: Float)?] = 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=?
|
||||
""", [chat.uuidString, vector.language]) { row in
|
||||
guard let score = vector.similarity(to: string(row, 1)), score >= 0.35 else { return nil }
|
||||
return (sqlite3_column_int64(row, 0), score)
|
||||
}
|
||||
semantic = candidates.compactMap { $0 }.sorted {
|
||||
$0.score == $1.score ? $0.id < $1.id : $0.score > $1.score
|
||||
}.prefix(24).map(\.id)
|
||||
}
|
||||
// Reciprocal rank fusion puts independently corroborated chunks ahead of single-signal hits.
|
||||
var scores: [Int64: Double] = [:]
|
||||
for ranking in [lexical, semantic] {
|
||||
for (offset, id) in ranking.enumerated() {
|
||||
scores[id, default: 0] += 1 / Double(61 + offset)
|
||||
}
|
||||
}
|
||||
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))
|
||||
let lexicalRanks = Dictionary(uniqueKeysWithValues: lexical.enumerated().map { ($0.element, $0.offset) })
|
||||
let ordered = scores.keys.sorted {
|
||||
if scores[$0] != scores[$1] { return scores[$0, default: 0] > scores[$1, default: 0] }
|
||||
let left = lexicalRanks[$0, default: .max]
|
||||
let right = lexicalRanks[$1, default: .max]
|
||||
return left == right ? $0 < $1 : left < right
|
||||
}
|
||||
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)
|
||||
return try ordered.prefix(4).flatMap { id in
|
||||
try query("""
|
||||
SELECT d.title, substr(i.content,1,1600), d.id, i.rowid
|
||||
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 }
|
||||
""", [String(id), chat.uuidString]) { try documentExcerpt($0, includeLocation: includeLocations) }
|
||||
}
|
||||
for excerpt in lexical where excerpts.count < 4 && !excerpts.contains(excerpt) { excerpts.append(excerpt) }
|
||||
return excerpts
|
||||
}
|
||||
|
||||
static func isWorkspaceBackup(_ url: URL) -> Bool {
|
||||
@@ -453,7 +503,11 @@ final class Store {
|
||||
let finish = sqlite3_backup_finish(backup)
|
||||
guard step == SQLITE_DONE, finish == SQLITE_OK else { throw failure }
|
||||
try preparePromptLibrary()
|
||||
try prepareWebSources()
|
||||
try prepareMessageSources()
|
||||
}
|
||||
|
||||
private func decodeArray<Element: Decodable>(_ text: String) -> [Element] {
|
||||
(try? JSONDecoder().decode([Element].self, from: Data(text.utf8))) ?? []
|
||||
}
|
||||
|
||||
private func execute(_ sql: String) throws {
|
||||
|
||||
Reference in New Issue
Block a user