-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.d
More file actions
65 lines (56 loc) · 1.96 KB
/
app.d
File metadata and controls
65 lines (56 loc) · 1.96 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
import dpq2;
import std.algorithm;
import std.conv;
import std.json;
import std.net.curl;
import std.process;
import std.range;
import std.stdio;
import std.typecons;
float[int][] embed(string[] inputs)
{
string url = "http://localhost:3000/embed_sparse";
JSONValue data;
data["inputs"] = inputs;
auto client = HTTP();
client.addRequestHeader("Content-Type", "application/json");
auto response = post(url, data.toString, client);
auto embeddings = parseJSON(response).array;
return embeddings.map!(e => assocArray(e.array.map!(v => tuple(cast(int) v["index"].integer, cast(float) v["value"].floating)))).array();
}
string sparsevec(float[int] elements, int dim)
{
return "{" ~ elements.byKeyValue.map!(e => to!string(e.key + 1) ~ ":" ~ to!string(e.value)).join(",") ~ "}/" ~ to!string(dim);
}
void main()
{
Connection conn = new Connection("postgres://localhost/pgvector_example");
conn.exec("CREATE EXTENSION IF NOT EXISTS vector");
conn.exec("DROP TABLE IF EXISTS documents");
conn.exec("CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding sparsevec(30522))");
string[] documents = [
"The dog is barking",
"The cat is purring",
"The bear is growling"
];
auto embeddings = embed(documents);
foreach (content, embedding; zip(documents, embeddings))
{
QueryParams p;
p.sqlCommand = "INSERT INTO documents (content, embedding) VALUES ($1, $2::sparsevec)";
p.argsVariadic(content, sparsevec(embedding, 30522));
conn.execParams(p);
}
string query = "forest";
auto queryEmbedding = embed([query])[0];
QueryParams p;
p.sqlCommand = "SELECT content FROM documents ORDER BY embedding <=> $1::sparsevec LIMIT 5";
p.argsVariadic(sparsevec(queryEmbedding, 30522));
p.resultFormat = ValueFormat.TEXT;
auto result = conn.execParams(p);
foreach (row; rangify(result))
{
writeln(row);
}
conn.destroy();
}