forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemporaryUSearch.swift
More file actions
164 lines (147 loc) · 5.27 KB
/
TemporaryUSearch.swift
File metadata and controls
164 lines (147 loc) · 5.27 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import Foundation
import USearch
import USearchObjective
@globalActor
private actor TemporaryUSearchActor {
static let shared = TemporaryUSearchActor()
}
#warning(
"It's not working yet because of a bug in USearch https://github.com/unum-cloud/usearch/issues/131"
)
/// A temporary USearch index for small and temporary documents.
public actor TemporaryUSearch: VectorStore {
public let identifier: String
let index: USearchIndex
var documents: [UInt32: Document] = [:]
var isViewOnly: Bool = false
public init(identifier: String) {
self.identifier = identifier
index = USearchIndex.make(
metric: .cos,
dimensions: 1536, // text-embedding-ada-002
connectivity: 16,
quantization: .F32
)
}
/// Load a USearch index if found.
public static func load(identifier: String) async -> TemporaryUSearch? {
let it = TemporaryUSearch(identifier: identifier)
do {
try await it.load()
return it
} catch {
return nil
}
}
/// Create a readonly USearch instance if the index is found.
public static func view(identifier: String) async -> TemporaryUSearch? {
let it = TemporaryUSearch(identifier: identifier)
do {
try await it.view()
return it
} catch {
return nil
}
}
public func save() {
index.save(path: Self.indexURLFromIdentifier(identifier).path)
if let documentsData = try? JSONEncoder().encode(documents) {
FileManager.default.createFile(
atPath: Self.documentURLFromIdentifier(identifier).path,
contents: documentsData,
attributes: nil
)
}
}
public func searchWithDistance(
embeddings: [Float],
count: Int
) async throws -> [(document: Document, distance: Float)] {
let embeddings = embeddings.map { Float32($0) }[...]
let result = index.search(vector: embeddings, count: count)
var matches = [(document: Document, distance: Float)]()
for (index, distance) in zip(result.0, result.1) {
if let document = documents[index] {
matches.append((document, distance))
}
}
return matches
}
public func clear() {
guard !isViewOnly else { return }
index.clear()
documents = [:]
}
public func add(_ documents: [EmbeddedDocument]) async throws {
guard !isViewOnly else { return }
let lastIndex = self.documents.keys.max() ?? 0
for (i, document) in documents.enumerated() {
let key = lastIndex + UInt32(i) + 1
let embeddings = document.embeddings.map { Float32($0) }[...]
index.add(label: key, vector: embeddings)
self.documents[key] = document.document
}
save()
}
public func set(_ documents: [EmbeddedDocument]) async throws {
guard !isViewOnly else { return }
clear()
for (i, document) in documents.enumerated() {
let embeddings = document.embeddings.map { Float32($0) }[...]
index.add(label: UInt32(i), vector: embeddings)
self.documents[UInt32(i)] = document.document
}
save()
}
enum LoadError: Error {
case indexNotFound
case documentsNotFound
}
func load() throws {
let indexURL = Self.indexURLFromIdentifier(identifier)
guard FileManager.default.fileExists(atPath: indexURL.path) else {
throw LoadError.indexNotFound
}
index.load(path: indexURL.path)
guard let documentsData = FileManager.default.contents(
atPath: Self.documentURLFromIdentifier(identifier).path
) else {
throw LoadError.documentsNotFound
}
let docs = try JSONDecoder().decode([UInt32: Document].self, from: documentsData)
documents = docs
}
func view() throws {
let indexURL = Self.indexURLFromIdentifier(identifier)
guard FileManager.default.fileExists(atPath: indexURL.path) else {
throw LoadError.indexNotFound
}
index.view(path: indexURL.path)
guard let documentsData = FileManager.default.contents(
atPath: Self.documentURLFromIdentifier(identifier).path
) else {
throw LoadError.documentsNotFound
}
let docs = try JSONDecoder().decode([UInt32: Document].self, from: documentsData)
documents = docs
isViewOnly = true
}
}
extension TemporaryUSearch {
static func indexURLFromIdentifier(_ identifier: String) -> URL {
let cacheDirectory = FileManager.default
.urls(for: .cachesDirectory, in: .userDomainMask)
.first!
let url = cacheDirectory
.appendingPathComponent("CopilotForXcode-USearchIndex-" + identifier + ".usearch")
return url
}
static func documentURLFromIdentifier(_ identifier: String) -> URL {
let cacheDirectory = FileManager.default
.urls(for: .cachesDirectory, in: .userDomainMask)
.first!
let url = cacheDirectory
.appendingPathComponent("CopilotForXcode-USearchDocument-" + identifier + ".usearch")
return url
}
}