-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEmbedder.php
60 lines (49 loc) · 1.59 KB
/
Embedder.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
52
53
54
55
56
57
58
59
60
<?php
declare(strict_types=1);
namespace App\Blog;
use Codewithkyrian\ChromaDB\Client;
use PhpLlm\LlmChain\Bridge\OpenAI\Embeddings;
use PhpLlm\LlmChain\Document\Vector;
use PhpLlm\LlmChain\Model\Response\AsyncResponse;
use PhpLlm\LlmChain\Model\Response\VectorResponse;
use PhpLlm\LlmChain\PlatformInterface;
final readonly class Embedder
{
public function __construct(
private Loader $loader,
private PlatformInterface $platform,
private Client $chromaClient,
) {
}
public function embedBlog(): void
{
$posts = $this->loader->load();
$vectors = $this->createEmbeddings($posts);
$this->pushToChromaDB($posts, $vectors);
}
/**
* @param Post[] $posts
*
* @return Vector[]
*/
private function createEmbeddings(array $posts): array
{
$texts = array_map(fn (Post $post) => $post->toString(), $posts);
$response = $this->platform->request(new Embeddings(), $texts);
assert($response instanceof AsyncResponse);
$response = $response->unwrap();
assert($response instanceof VectorResponse);
return $response->getContent();
}
/**
* @param Post[] $posts
* @param Vector[] $vectors
*/
private function pushToChromaDB(array $posts, array $vectors): void
{
$collection = $this->chromaClient->getOrCreateCollection('symfony_blog');
$ids = array_map(fn (Post $post) => $post->id, $posts);
$vectors = array_map(fn (Vector $vector) => $vector->getData(), $vectors);
$collection->upsert($ids, $vectors, $posts);
}
}