Skip to content

Instantly share code, notes, and snippets.

@Braunson
Created November 19, 2022 21:39
Show Gist options
  • Select an option

  • Save Braunson/2f90d04d7893c6aef18d1194db626768 to your computer and use it in GitHub Desktop.

Select an option

Save Braunson/2f90d04d7893c6aef18d1194db626768 to your computer and use it in GitHub Desktop.
Pinecone.io Service Class
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class Pinecone
{
protected $service;
protected string $index;
protected string $endpoint;
protected string $indexEndpoint;
public function __construct(Http $http)
{
$this->endpoint = 'https://controller.'.config('services.pinecone.env').'.pinecone.io';
$this->service = $http::withHeaders([
'Api-Key' => config('services.pinecone.key'),
])->throw();
}
/** Helper to set the index and index endpoint */
public function setIndex(string $index_name): self
{
$this->index = $index_name;
$this->indexEndpoint = 'https://'.$index_name.'-'.config('services.pinecone.project_id').'.svc.'.config('services.pinecone.env').'.pinecone.io';
return $this;
}
/** Check if given index exists */
public function indexExists(string $index_name): bool
{
$indexes = $this->service
->get($this->endpoint.'/databases')
->json();
return in_array($index_name, $indexes);
}
/** Create a new index */
public function createIndex(string $index_name): bool
{
$body = [
'name' => $index_name,
'dimension' => config('services.openai.dimensions'),
'metric' => 'cosine',
'pods' => 1,
// S1 = best storage capacity
// P1 = faster queries
// P2 = lower latency, highest throughput
'pod_type' => 'p1',
'index_config' => [
'kbits' => 512,
],
];
$response = $this->service
->post($this->endpoint.'/databases', $body);
abort_if(
$response->failed(),
$response->json()
);
return true;
}
/** Upsert vector data into an index */
public function upsertIndex(array $data): bool
{
abort_if(
empty($this->index) || empty($this->indexEndpoint),
'Please set an index first using setIndex()'
);
$response = $this->service
->post($this->indexEndpoint.'/vectors/upsert', $data);
abort_if(
$response->failed(),
$response->json()
);
return true;
}
/** Query something */
public function query($data)
{
abort_if(
empty($this->index) || empty($this->indexEndpoint),
'Please set an index first using setIndex()'
);
$response = $this->service
->post($this->indexEndpoint.'/query', $data);
abort_if(
$response->failed(),
$response->json()
);
return $response->json();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment