-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathexample.php
51 lines (42 loc) · 1.57 KB
/
example.php
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
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Pgvector\Vector;
$db = pg_connect('postgres://localhost/pgvector_example');
pg_query($db, 'CREATE EXTENSION IF NOT EXISTS vector');
pg_query($db, 'DROP TABLE IF EXISTS documents');
pg_query($db, 'CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding vector(1536))');
function fetchEmbeddings($input)
{
$apiKey = getenv('OPENAI_API_KEY') or die("Set OPENAI_API_KEY\n");
$url = 'https://api.openai.com/v1/embeddings';
$data = [
'input' => $input,
'model' => 'text-embedding-3-small'
];
$opts = [
'http' => [
'method' => 'POST',
'header' => "Authorization: Bearer $apiKey\r\nContent-Type: application/json\r\n",
'content' => json_encode($data)
]
];
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return array_map(fn ($v) => $v['embedding'], json_decode($response, true)['data']);
}
$input = [
'The dog is barking',
'The cat is purring',
'The bear is growling'
];
$embeddings = fetchEmbeddings($input);
foreach ($input as $i => $content) {
pg_query_params($db, 'INSERT INTO documents (content, embedding) VALUES ($1, $2)', [$content, new Vector($embeddings[$i])]);
}
$documentId = 2;
$result = pg_query_params($db, 'SELECT * FROM documents WHERE id != $1 ORDER BY embedding <=> (SELECT embedding FROM documents WHERE id = $1) LIMIT 5', [$documentId]);
while ($row = pg_fetch_array($result)) {
echo $row['content'] . "\n";
}
pg_free_result($result);
pg_close($db);