-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.cr
More file actions
40 lines (34 loc) · 1.18 KB
/
example.cr
File metadata and controls
40 lines (34 loc) · 1.18 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
require "db"
require "http/client"
require "json"
require "pg"
db = DB.open("postgres://localhost/pgvector_example")
db.exec "CREATE EXTENSION IF NOT EXISTS vector"
db.exec "DROP TABLE IF EXISTS documents"
db.exec "CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding vector(1536))"
def embed(input)
api_key = ENV.fetch("OPENAI_API_KEY")
url = "https://api.openai.com/v1/embeddings"
data = {
"input" => input,
"model" => "text-embedding-3-small",
}
headers = HTTP::Headers.new
headers["Authorization"] = "Bearer #{api_key}"
headers["Content-Type"] = "application/json"
response = HTTP::Client.post url, headers, data.to_json
JSON.parse(response.body)["data"].as_a.map { |v| v["embedding"] }
end
documents = ["The dog is barking", "The cat is purring", "The bear is growling"]
embeddings = embed(documents)
documents.zip(embeddings) do |content, embedding|
db.exec "INSERT INTO documents (content, embedding) VALUES ($1, $2)", content, embedding.to_json
end
query = "forest"
embedding = embed([query])[0]
db.query("SELECT content FROM documents ORDER BY embedding <=> $1 LIMIT 5", embedding) do |rs|
rs.each do
puts rs.read(String)
end
end
db.close