Skip to content

Commit 1443c3c

Browse files
committed
Added halfvec example for OpenAI [skip ci]
1 parent ac9e398 commit 1443c3c

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

examples/openai/halfvec.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from openai import OpenAI
2+
from pgvector.psycopg import register_vector, HalfVector
3+
import psycopg
4+
5+
conn = psycopg.connect(dbname='pgvector_example', autocommit=True)
6+
7+
conn.execute('CREATE EXTENSION IF NOT EXISTS vector')
8+
register_vector(conn)
9+
10+
conn.execute('DROP TABLE IF EXISTS documents')
11+
conn.execute('CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding halfvec(3072))')
12+
conn.execute('CREATE INDEX ON documents USING hnsw (embedding halfvec_cosine_ops)')
13+
14+
15+
def embed(input):
16+
client = OpenAI()
17+
response = client.embeddings.create(input=input, model='text-embedding-3-large')
18+
return [v.embedding for v in response.data]
19+
20+
21+
input = [
22+
'The dog is barking',
23+
'The cat is purring',
24+
'The bear is growling'
25+
]
26+
embeddings = embed(input)
27+
for content, embedding in zip(input, embeddings):
28+
conn.execute('INSERT INTO documents (content, embedding) VALUES (%s, %s)', (content, HalfVector(embedding)))
29+
30+
query = 'forest'
31+
query_embedding = embed([query])[0]
32+
result = conn.execute('SELECT content FROM documents ORDER BY embedding <=> %s LIMIT 5', (HalfVector(query_embedding),)).fetchall()
33+
for row in result:
34+
print(row[0])

0 commit comments

Comments
 (0)