-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.nim
More file actions
49 lines (41 loc) · 1.52 KB
/
example.nim
File metadata and controls
49 lines (41 loc) · 1.52 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
import db_connector/db_postgres
import pgvector
import std/[envvars, httpclient, json, sequtils, sugar]
let db = db_postgres.open("localhost", "", "", "pgvector_example")
db.exec(sql"CREATE EXTENSION IF NOT EXISTS vector")
db.exec(sql"DROP TABLE IF EXISTS documents")
db.exec(sql"CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding vector(1536))")
proc embed(input: openArray[string]): seq[seq[float]] =
let url = "https://api.openai.com/v1/embeddings"
let body = %*{
"input": input,
"model": "text-embedding-3-small"
}
let client = newHttpClient()
client.headers = newHttpHeaders({
"Authorization": "Bearer " & getenv("OPENAI_API_KEY"),
"Content-Type": "application/json"
})
try:
let response = client.request(url, httpMethod = HttpPost, body = $body)
let data = parseJson(response.bodyStream)["data"]
collect(newSeqOfCap(data.len)):
for obj in data:
collect(newSeqOfCap(obj["embedding"].len)):
for v in obj["embedding"]: v.getFloat()
finally:
client.close()
let input = [
"The dog is barking",
"The cat is purring",
"The bear is growling"
]
let embeddings = embed(input)
for (content, embedding) in zip(input, embeddings):
db.exec(sql"INSERT INTO documents (content, embedding) VALUES (?, ?)", content, embedding.toVector)
let query = "forest"
let queryEmbedding = embed([query])[0]
let rows = db.getAllRows(sql"SELECT content FROM documents ORDER BY embedding <=> ? LIMIT 5", queryEmbedding.toVector)
for row in rows:
echo row[0]
db.close()