-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
148 lines (124 loc) · 3.17 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
142
143
144
145
146
147
148
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
)
func main() {
apiKey := os.Getenv("CO_API_KEY")
if apiKey == "" {
fmt.Println("Set CO_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 = 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 bit(1024))")
if err != nil {
panic(err)
}
input := []string{
"The dog is barking",
"The cat is purring",
"The bear is growling",
}
embeddings, err := Embed(input, "search_document", apiKey)
if err != nil {
panic(err)
}
for i, content := range input {
_, err := conn.Exec(ctx, "INSERT INTO documents (content, embedding) VALUES ($1, $2)", content, PgBit(embeddings[i]))
if err != nil {
panic(err)
}
}
query := "forest"
queryEmbedding, err := Embed([]string{query}, "search_query", apiKey)
if err != nil {
panic(err)
}
rows, err := conn.Query(ctx, "SELECT id, content FROM documents ORDER BY embedding <~> $1 LIMIT 5", PgBit(queryEmbedding[0]))
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 embedRequest struct {
Texts []string `json:"texts"`
Model string `json:"model"`
InputType string `json:"input_type"`
EmbeddingTypes []string `json:"embedding_types"`
}
func Embed(texts []string, inputType string, apiKey string) ([][]byte, error) {
url := "https://api.cohere.com/v1/embed"
data := &embedRequest{
Texts: texts,
Model: "embed-english-v3.0",
InputType: inputType,
EmbeddingTypes: []string{"ubinary"},
}
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 [][]byte
for _, item := range result["embeddings"].(map[string]interface{})["ubinary"].([]interface{}) {
embedding := make([]byte, 0, len(item.([]interface{})))
for _, v := range item.([]interface{}) {
embedding = append(embedding, uint8(v.(float64)))
}
embeddings = append(embeddings, embedding)
}
return embeddings, nil
}
func PgBit(b []byte) pgtype.Bits {
return pgtype.Bits{Bytes: b, Len: int32(len(b) * 8), Valid: true}
}