-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
141 lines (118 loc) · 2.92 KB
/
main.go
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/jackc/pgx/v5"
"github.com/pgvector/pgvector-go"
pgxvector "github.com/pgvector/pgvector-go/pgx"
)
func main() {
apiKey := os.Getenv("OPENAI_API_KEY")
if apiKey == "" {
fmt.Println("Set OPENAI_API_KEY")
os.Exit(1)
}
ctx := context.Background()
conn, err := pgx.Connect(ctx, "postgres://localhost/pgvector_example")
if err != nil {
panic(err)
}
defer conn.Close(ctx)
_, err = conn.Exec(ctx, "CREATE EXTENSION IF NOT EXISTS vector")
if err != nil {
panic(err)
}
err = pgxvector.RegisterTypes(ctx, conn)
if err != nil {
panic(err)
}
_, err = conn.Exec(ctx, "DROP TABLE IF EXISTS documents")
if err != nil {
panic(err)
}
_, err = conn.Exec(ctx, "CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding vector(1536))")
if err != nil {
panic(err)
}
input := []string{
"The dog is barking",
"The cat is purring",
"The bear is growling",
}
embeddings, err := FetchEmbeddings(input, apiKey)
if err != nil {
panic(err)
}
for i, content := range input {
_, err := conn.Exec(ctx, "INSERT INTO documents (content, embedding) VALUES ($1, $2)", content, pgvector.NewVector(embeddings[i]))
if err != nil {
panic(err)
}
}
documentId := 1
rows, err := conn.Query(ctx, "SELECT id, content FROM documents WHERE id != $1 ORDER BY embedding <=> (SELECT embedding FROM documents WHERE id = $1) LIMIT 5", documentId)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var id int64
var content string
err = rows.Scan(&id, &content)
if err != nil {
panic(err)
}
fmt.Println(id, content)
}
if rows.Err() != nil {
panic(rows.Err())
}
}
type apiRequest struct {
Input []string `json:"input"`
Model string `json:"model"`
}
func FetchEmbeddings(input []string, apiKey string) ([][]float32, error) {
url := "https://api.openai.com/v1/embeddings"
data := &apiRequest{
Input: input,
Model: "text-embedding-3-small",
}
b, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", apiKey))
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Bad status code: %d", resp.StatusCode)
}
var result map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return nil, err
}
var embeddings [][]float32
for _, item := range result["data"].([]interface{}) {
var embedding []float32
for _, v := range item.(map[string]interface{})["embedding"].([]interface{}) {
embedding = append(embedding, float32(v.(float64)))
}
embeddings = append(embeddings, embedding)
}
return embeddings, nil
}