|
2 | 2 |
|
3 | 3 | namespace NeuronAI\RAG\VectorStore;
|
4 | 4 |
|
| 5 | +use GuzzleHttp\Client; |
| 6 | +use GuzzleHttp\RequestOptions; |
5 | 7 | use NeuronAI\RAG\Document;
|
6 |
| -use \Probots\Pinecone\Client; |
7 | 8 |
|
8 | 9 | class PineconeVectorStore implements VectorStoreInterface
|
9 | 10 | {
|
| 11 | + protected Client $client; |
| 12 | + |
10 | 13 | public function __construct(
|
11 |
| - protected Client $client, |
12 |
| - protected string $indexName |
| 14 | + string $key, |
| 15 | + protected string $indexName, |
| 16 | + array $spec, |
| 17 | + string $version = '2025-01' |
13 | 18 | ) {
|
14 |
| - // todo: setup the vector index |
| 19 | + $this->client = new Client([ |
| 20 | + 'base_uri' => 'https://api.pinecone.io', |
| 21 | + 'headers' => [ |
| 22 | + 'Accept' => 'application/json', |
| 23 | + 'Content-Type' => 'application/json', |
| 24 | + 'Api-Key' => $key, |
| 25 | + 'X-Pinecone-API-Version' => $version, |
| 26 | + ] |
| 27 | + ]); |
| 28 | + |
| 29 | + $response = $this->client->get("indexes/{$this->indexName}"); |
| 30 | + |
| 31 | + if ($response->getStatusCode() === 200) { |
| 32 | + return; |
| 33 | + } |
15 | 34 |
|
16 |
| - // https://github.com/probots-io/pinecone-php |
| 35 | + // Create the index |
| 36 | + $this->client->post('indexes', [ |
| 37 | + RequestOptions::JSON => [ |
| 38 | + 'name' => $indexName, |
| 39 | + 'spec' => $spec, |
| 40 | + ] |
| 41 | + ]); |
17 | 42 | }
|
18 | 43 |
|
19 | 44 | public function addDocument(Document $document): void
|
20 | 45 | {
|
21 |
| - // TODO: Implement addDocument() method. |
| 46 | + $this->addDocuments([$document]); |
22 | 47 | }
|
23 | 48 |
|
24 | 49 | public function addDocuments(array $documents): void
|
25 | 50 | {
|
26 |
| - // TODO: Implement addDocuments() method. |
| 51 | + $this->client->post("indexes/{$this->indexName}/vectors/upsert", [ |
| 52 | + RequestOptions::JSON => array_map(function (Document $document) { |
| 53 | + return [ |
| 54 | + 'id' => $document->id??uniqid(), |
| 55 | + 'values' => $document->embedding, |
| 56 | + ]; |
| 57 | + }, $documents) |
| 58 | + ]); |
27 | 59 | }
|
28 | 60 |
|
29 | 61 | public function similaritySearch(array $embedding, int $k = 4): iterable
|
30 | 62 | {
|
31 |
| - // TODO: Implement similaritySearch() method. |
| 63 | + $result = $this->client->get("indexes/{$this->indexName}/query", [ |
| 64 | + RequestOptions::QUERY => [ |
| 65 | + 'namespace' => '', |
| 66 | + 'vector' => $embedding, |
| 67 | + 'top_k' => $k, |
| 68 | + ] |
| 69 | + ])->getBody()->getContents(); |
| 70 | + |
| 71 | + $result = json_decode($result, true); |
| 72 | + |
| 73 | + return $result['matches']; |
32 | 74 | }
|
33 | 75 | }
|
0 commit comments